BZOJ 1935: [Shoi2007]Tree 园丁的烦恼

来源:互联网 发布:女网络歌手 编辑:程序博客网 时间:2024/05/21 10:45

Description

很久很久以前,在遥远的大陆上有一个美丽的国家。统治着这个美丽国家的国王是一个园艺爱好者,在他的皇家花园里种植着各种奇花异草。有一天国王漫步在花园里,若有所思,他问一个园丁道: “最近我在思索一个问题,如果我们把花坛摆成六个六角形,那么……” “那么本质上它是一个深度优先搜索,陛下”,园丁深深地向国王鞠了一躬。 “嗯……我听说有一种怪物叫九头蛇,它非常贪吃苹果树……” “是的,显然这是一道经典的动态规划题,早在N元4002年我们就已经发现了其中的奥秘了,陛下”。 “该死的,你究竟是什么来头?” “陛下息怒,干我们的这行经常莫名其妙地被问到和OI有关的题目,我也是为了预防万一啊!” 王者的尊严受到了伤害,这是不可容忍的。看来一般的难题是难不倒这位园丁的,国王最后打算用车轮战来消耗他的实力: “年轻人,在我的花园里的每一棵树可以用一个整数坐标来表示,一会儿,我的骑士们会来轮番询问你某一个矩阵内有多少树,如果你不能立即答对,你就准备走人吧!”说完,国王气呼呼地先走了。 这下轮到园丁傻眼了,他没有准备过这样的问题。所幸的是,作为“全国园丁保护联盟”的会长——你,可以成为他的最后一根救命稻草。

Input

第一行有两个整数n,m(0≤n≤500000,1≤m≤500000)。n代表皇家花园的树木的总数,m代表骑士们询问的次数。 文件接下来的n行,每行都有两个整数xi,yi,代表第i棵树的坐标(0≤xi,yi≤10000000)。 文件的最后m行,每行都有四个整数aj,bj,cj,dj,表示第j次询问,其中所问的矩形以(aj,bj)为左下坐标,以(cj,dj)为右上坐标。

Output

共输出m行,每行一个整数,即回答国王以(aj,bj)和(cj,dj)为界的矩形里有多少棵树。

Sample Input

3 1

0 0

0 1

1 0

0 0 1 1

Sample Output

3

分析

离散后拆成4个询问然后树状数组

代码

#include <bits/stdc++.h>const int N = 500005;int read(){    int x = 0, f = 1;    char ch = getchar();    while (ch < '0' || ch > '9') {if (ch == '-') f = -1; ch = getchar();}    while (ch >= '0' && ch <= '9') {x = x * 10 + ch - '0'; ch = getchar();}    return x * f;}int w[N * 5], s[N * 5];int w1, tot;struct Note{    int op,x,y,id,val;}q[N * 5];int ans[N];bool cmp(Note a,Note b){    return a.x < b.x || a.x == b.x && a.op < b.op;}void updata(int x,int y){    while (x <= w1)    {        s[x] += y;        x += x & (-x);    }}int query(int x){    int res = 0;    while (x)    {        res += s[x];        x -= x & (-x);    }    return res;}int main(){    int n = read(), m = read();    for (int i = 1; i <= n; i++)        q[++tot].x = read(), q[tot].y = read(), q[tot].op = 0, w[++w1] = q[i].y;    for (int i = 1; i <= m; i++)    {        int x1 = read(), y1 = read(), x2 = read(), y2 = read();        q[++tot].x = x1 - 1, q[tot].y = y1 - 1, q[tot].op = 1, q[tot].id = i, q[tot].val = 1; w[++w1] = q[tot].y;        q[++tot].x = x2, q[tot].y = y1 - 1, q[tot].op = 1, q[tot].id = i, q[tot].val = -1; w[++w1] = q[tot].y;        q[++tot].x = x1 - 1, q[tot].y = y2, q[tot].op = 1, q[tot].id = i, q[tot].val = -1; w[++w1] = q[tot].y;        q[++tot].x = x2, q[tot].y = y2, q[tot].op = 1, q[tot].id = i, q[tot].val = 1, w[++w1] = q[tot].y;    }    std::sort(w + 1, w + w1 + 1);    w1 = std::unique(w + 1, w + w1 + 1) - w - 1;    for (int i = 1; i <= tot; i++)        q[i].y = std::lower_bound(w + 1, w + w1 + 1, q[i].y) - w;    std::sort(q + 1, q + tot + 1, cmp);    for (int i = 1; i <= tot; i++)    {        if (q[i].op == 0)            updata(q[i].y, 1);        else        {            ans[q[i].id] += q[i].val * query(q[i].y);        }    }    for (int i = 1; i <= m; i++)        printf("%d\n",ans[i]);}
原创粉丝点击