HDUOJ1264 Counting Squares(扫描线解法)

HDUOJ1264 Counting Squares

题意:

很裸很裸的求面积并问题

分析:

也没啥好分析的,就是个板子题
但是这题有个坑点,输入的对角坐标并不一定是按左下、右上的顺序,需要自行判断
我因为这个WA了5发…

代码:

#include 
using namespace std;
#define pr(x) cout << #x << " = " << x << "  "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e6 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;

int n;
struct Seg
{
    int l, r, h;
    int d;
    Seg() {}
    Seg(int l, int r, int h, int d) : l(l), r(r), h(h), d(d) {}
    bool operator<(const Seg &rhs) const { return h < rhs.h; }
} a[N];

int cnt[N << 2];
int sum[N << 2], all[N];

#define lson l, m, rt << 1
#define rson m + 1, r, rt << 1 | 1

void push_up(int l, int r, int rt)
{
    if (cnt[rt])
        sum[rt] = all[r + 1] - all[l];
    else if (l == r)
        sum[rt] = 0;
    else
        sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}

void update(int L, int R, int v, int l, int r, int rt)
{
    if (L <= l && r <= R)
    {
        cnt[rt] += v;
        push_up(l, r, rt);
        return;
    }
    int m = l + r >> 1;
    if (L <= m)
        update(L, R, v, lson);
    if (R > m)
        update(L, R, v, rson);
    push_up(l, r, rt);
}

int main()
{
    int x1, y1, x2, y2;
    int num = 0;
    int ans = 0;
    while (~scanf("%d%d%d%d", &x1, &y1, &x2, &y2))
    {
        if ((x1 == -1 && y1 == -1 && x2 == -1 && y2 == -1) || (x1 == -2 && y1 == -2 && x2 == -2 && y2 == -2))
        {
            sort(a + 1, a + 1 + num);
            sort(all + 1, all + 1 + num);
            int m = unique(all + 1, all + 1 + num) - all - 1;

            memset(cnt, 0, sizeof cnt);
            memset(sum, 0, sizeof sum);

            for (int i = 1; i < num; ++i)
            {
                int l = lower_bound(all + 1, all + 1 + m, a[i].l) - all;
                int r = lower_bound(all + 1, all + 1 + m, a[i].r) - all;
                if (l < r)
                    update(l, r - 1, a[i].d, 1, m, 1);
                ans += sum[1] * (a[i + 1].h - a[i].h);
            }
            printf("%d\n", ans);
            num = 0, ans = 0;

            if (x1 == -2)
                break;
        }

        ++num;
        a[num] = Seg(min(x1, x2), max(x1, x2), min(y1, y2), 1);
        all[num] = x1;
        ++num;
        a[num] = Seg(min(x1, x2), max(x1, x2), max(y1, y2), -1);
        all[num] = x2;
    }
    return 0;
}

你可能感兴趣的:(扫描线)