4357: 男生女生配
Time Limit: 6 Sec Memory Limit: 128 MB
Submit: 87 Solved: 2
Description
有 n 个女生和 m 个男生参加相亲活动,但他们一开始被主办方安排到了不同的地方。
因为是在城市中,所以两点(x, y),(a, b)间的距离可以近似看成 |x-a| + |y-b|。
现在请你对于每个男生,都算出离他最近的女生的距离。
Input
多组测试。每组输入形如:
n
x1 y1
x2 y2
…
xn yn
m
x1 y1
x2 y2
…
xm ym
1<=n, m, xi, yi<=200000
Output
每组输出形如:
ans(1)
ans(2)
…
ans(m)
Sample Input
4
1 3
2 3
4 5
9 1
4
1 3
2 5
5 5
10 1
Sample Output
0
2
1
1
题意:
做法:用数状数组维护前缀后缀最大值,先把所有的点按照y的大小排序,作为数状数组的下标pos,然后先处理比男生(x0,y0),对于纵坐标比y0大的点,保存x+maxn-y,按照pos维护后缀最大值,对于比y0小的点,保存x+y,维护前缀最大值,建两棵树,分别维护前缀最大x+y,和后缀最大x+maxn-y,对于男生(x0,y0)只需找出比y0小的最大x+y,和比y0打的最大的x+maxn-y,这样就可以维护比男生x小的最小值,然后再按照x的大小从大到小排序,找出比他x大的最小,
#include<bits/stdc++.h>
using namespace std;
const int N = 400007;
struct node{
int x,y,id;
};
int n,m;
node pt[N];
int sum[N],sum2[N],pos[N],ans[N];
bool cmp(node a,node b){
if(a.x == b.x) return a.id < b.id;
return a.x < b.x;
}
bool cmp2(node a,node b){
if(a.x == b.x) return a.id < b.id;
return a.x > b.x;
}
bool cmp3(node a,node b){
return a.y < b.y;
}
int lowbit(int x){
return x&(-x);
}
void update(int *a,int x,int d,int op){
if(op==0){
while(x){
a[x] = max(a[x],d);
x -= lowbit(x);
}
}
else{
while(x <= n+m){
a[x] = max(a[x],d);
x += lowbit(x);
}
}
}
int query(int *a,int x,int op){
int ret = -1e9;
if(op==0){
while(x <= n+m){
ret = max(a[x],ret);
x += lowbit(x);
}
}
else {
while(x){
ret = max(ret,a[x]);
x -= lowbit(x);
}
}
return ret;
}
int main(){
while(scanf("%d",&n)==1){
for(int i = 1;i<= n;i ++) scanf("%d %d",&pt[i].x,&pt[i].y),pt[i].id = i;
scanf("%d",&m);
for(int i = 1;i<= m;i ++) scanf("%d %d",&pt[i+n].x,&pt[i+n].y),pt[i+n].id = i+n;
sort(pt+1,pt+1+n+m,cmp3);
for(int i = 1;i <= n+m;i ++){
pos[pt[i].id] = i;
}
memset(sum,0xf7,sizeof(sum));
memset(sum2,0xf7,sizeof(sum2));
memset(ans,0x3f,sizeof(ans));
sort(pt+1,pt+1+n+m,cmp);
for(int i = 1;i <= n+m;i ++){
if(pt[i].id <= n){
update(sum,pos[pt[i].id],pt[i].x+pt[i].y,1);
update(sum2,pos[pt[i].id],pt[i].x+N-pt[i].y,0);
}
else{
int ret1 = query(sum,pos[pt[i].id],1);
int ret2 = query(sum2,pos[pt[i].id],0);
ans[pt[i].id] = min(ans[pt[i].id],pt[i].x+pt[i].y-ret1);
ans[pt[i].id] = min(ans[pt[i].id],pt[i].x+N-pt[i].y-ret2);
}
}
sort(pt+1,pt+n+m+1,cmp2);
memset(sum,0xf7,sizeof(sum));
memset(sum2,0xf7,sizeof(sum2));
for(int i = 1;i <= n+m;i ++){
if(pt[i].id <= n){
update(sum,pos[pt[i].id],N-pt[i].x+pt[i].y,1);
update(sum2,pos[pt[i].id],N-pt[i].x+N-pt[i].y,0);
}
else{
int ret1 = query(sum,pos[pt[i].id],1);
int ret2 = query(sum2,pos[pt[i].id],0);
ans[pt[i].id] = min(ans[pt[i].id],N-pt[i].x+pt[i].y-ret1);
ans[pt[i].id] = min(ans[pt[i].id],N-pt[i].x+N-pt[i].y-ret2);
}
}
for(int i = 1+n;i <=n+ m;i ++){
printf("%d\n",ans[i]);
}
}
return 0;
}