USACO window area 漂浮法

  这道题是求解几个矩形未被遮挡的面积问题, 可以使用漂浮法来解决, 什么事漂浮法请看这里http://www.nocow.cn/index.php/USACO/window, 代码如下:

/*
    ID: m1500293
    LANG: C++
    PROG: window
*/
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;
char s[80];

int buttom, top;
struct Window
{
    char name;
    int x1, y1, x2, y2;
}win[110];
int nwin;

void ocreate(char a[])
{
    char n;
    int x1, y1, x2, y2;
    sscanf(a, "w(%c,%d,%d,%d,%d)", &n, &x1, &y1, &x2, &y2);
    if(x1 > x2) swap(x1, x2);
    if(y1 > y2) swap(y1, y2);
    nwin++;
    for(int i=nwin-1; i>=1; i--)
        win[i] = win[i-1];
    win[0] = (Window){n, x1, y1, x2, y2};
}

void otop(char s[])
{
    char n = s[2];
    int idx = -1;
    for(int i=0; i<nwin; i++) if(win[i].name == n) {idx=i; break;}
    Window tp = win[idx];
    for(int i=idx; i>=1; i--) win[i] = win[i-1];
    win[0] = tp;
}

void obt(char s[])
{
    char n = s[2];
    int idx = -1;
    for(int i=0; i<nwin; i++) if(win[i].name == n) {idx=i; break;}
    Window tp = win[idx];
    for(int i=idx; i<nwin-1; i++)
        win[i] = win[i+1];
    win[nwin-1] = tp;
}
void od(char s[])
{
    char n = s[2];
    int idx = -1;
    for(int i=0; i<nwin; i++) if(win[i].name == n) {idx=i; break;}
    for(int i=idx; i<nwin-1; i++)
        win[i] = win[i+1];
    nwin--;
}

double area;

void dfs(int k, int x1, int y1, int x2, int y2)
{
    if(k==-1) { area += (x2-x1)*(y2-y1);  return; }
    if(k>=0 && (win[k].x1>=x2||win[k].x2<=x1||win[k].y1>=y2||win[k].y2<=y1))
    {
        dfs(k-1, x1, y1, x2, y2);
        return ;
    }
    if(win[k].x1>x1) { dfs(k-1, x1, y1, win[k].x1, y2); x1=win[k].x1; }
    if(win[k].y1>y1) { dfs(k-1, x1, y1, x2, win[k].y1); y1=win[k].y1; }
    if(win[k].x2<x2) { dfs(k-1, win[k].x2, y1, x2, y2); x2=win[k].x2; }
    if(win[k].y2<y2) { dfs(k-1, x1, win[k].y2, x2, y2); y2=win[k].y2; }
}

void os(char s[])
{
    area = 0.0;
    int idx = -1;
    for(int i=0; i<nwin; i++) if(win[i].name == s[2]) { idx=i; break; }
    dfs(idx-1, win[idx].x1, win[idx].y1, win[idx].x2, win[idx].y2);
    int x1=win[idx].x1, x2=win[idx].x2, y1=win[idx].y1, y2=win[idx].y2;
    printf("%.3f\n", area/((x2-x1)*(y2-y1))*100);
}
int main()
{
    freopen("window.in", "r", stdin);
    freopen("window.out", "w", stdout);
    nwin = 0;
    while(scanf("%s", s) != EOF)
    {
        switch(s[0])
        {
        case 'w':
            ocreate(s);
            break;
        case 't':
            otop(s);
            break;
        case 'b':
            obt(s);
            break;
        case 'd':
            od(s);
            break;
        case 's':
            os(s);
            break;
        }
    }
    return 0;
}

 

你可能感兴趣的:(USACO window area 漂浮法)