(SHOI2007) 平面内有 N 个点,有 M 个查询,每次询问一个以 ( Ai, Bi ) 为左下角,( Ci, Di ) 为右上角的矩形内有多少个点
这种问题首先想到的应该是二维线段树或者树状数组,但是这道题中 N, M 都是 500000,二维的肯定为超出空间限制,这能用一维。同时这道题中没有中途修改操作,所以可以离线做。把这些点离散化,询问的点也算在内,按 X 为第一关键字,是否为插入的点为第二关键字排序,这样就能做到先插入点,再查询。询问计算个数时,都按以 ( 0, 0 ) 为左下角的矩阵,用树状数组查询,这样能做到 O( logn ),之后和差一下就行。
#include
#include
using namespace std;
#define lowbit(x) (x & (-x))
const int MAX_N = 500005;
struct node{
int x, y, id, f;
friend bool operator<(const node& a, const node& b){
return a.x < b.x || (a.x == b.x && a.f < b.f);
} // sort x
}Q[MAX_N * 5];
inline int read()
{
int ret = 0, f = 1; char c = getchar();
while (!(c >= '0' && c <= '9')){ if (c == '-') f = -1; c = getchar(); }
while (c >= '0' && c <= '9') ret = ret*10 + c-'0', c = getchar();
return ret;
}
int N, M, x[MAX_N], y[MAX_N], st[MAX_N * 3];
int a[MAX_N], b[MAX_N], c[MAX_N], d[MAX_N];
int tot = 0, all = 0, tree[MAX_N][5]; // lisan, sum, ans
int s[MAX_N * 3]; // tree
int got(int x)
{
int l = 1, r = tot;
while(l <= r){
int mid = (l+r) >> 1;
if(st[mid] == x) return mid;
else if(st[mid] > x) r = mid - 1;
else l = mid + 1;
}
}
void tree_add(int x)
{
for (int i=x; i<=tot; i += lowbit(i))
s[i] += 1;
}
int tree_query(int x)
{
int ret = 0;
for(int i = x; i; i -= lowbit(i))
ret += s[i];
return ret;
}
void work(void)
{
sort(Q+1, Q+all+1);
for (int i=1; i<=all; i++){
printf("%d %d %d %d\n", Q[i].x, Q[i].y, Q[i].id, Q[i].f);
if(!Q[i].f) tree_add(Q[i].y);
else {
int t = tree_query(Q[i].y);
// printf("%d %d ", Q[i].x, Q[i].y); printf("%d\n", t);
tree[Q[i].id][Q[i].f] = t;
}
}
}
void doit(void)
{
sort(st+1, st+tot+1);
for (int i=1; i<=N; i++){
y[i] = got(y[i]);
Q[++ all].x = x[i]; Q[all].y = y[i];
}
for (int i=1; i<=M; i++){
b[i] = got(b[i]); d[i] = got(d[i]);
Q[++ all].x = c[i], Q[all].y = d[i], Q[all].id = i, Q[all].f = 1;
Q[++ all].x = a[i] , Q[all].y = d[i], Q[all].id = i, Q[all].f = 2;
Q[++ all].x = c[i], Q[all].y = b[i] , Q[all].id = i, Q[all].f = 3;
Q[++ all].x = a[i] , Q[all].y = b[i] , Q[all].id = i, Q[all].f = 4;
}
work();
for (int i=1; i<=M; i++){
int ans = 0; ans = tree[i][1] + tree[i][4] - tree[i][2] - tree[i][3];
//printf("%d %d %d %d\n", tree[i][1], tree[i][4], tree[i][2], tree[i][3]);
//printf("%d\n", ans);
}
return;
}
int main(void)
{
N = read(); M = read();
for (int i=1; i<=N; i++) x[i] = read(), y[i] = read(), st[++ tot] = y[i];
for (int i=1; i<=M; i++)
a[i] = read(), b[i] = read(), c[i] = read(), d[i] = read(),
st[++ tot] = b[i], st[++ tot] = d[i];
doit();
return 0;
}