Problem Buildnode
题目大意ide
n个点,每一个点有两个属性(x,y)。ui
对于每一个点i,询问一个 y 属性大于i ,x属性与 i 相差最小的点。spa
解题分析code
对于n个点,先以y为关键字进行降序排序。blog
对于每一个点的x用set来维护,每次询问时寻找当前点的前驱和后继,比较一下x属性的差值便可。排序
参考程序string
1 #include <cstdio> 2 #include <cstring> 3 #include <cmath> 4 #include <algorithm> 5 #include <set> 6 using namespace std; 7 8 #define N 200008 9 10 struct node{ 11 int x,p,pos; 12 node(int xx=0,int pp=0,int ppos=0):x(xx),p(pp),pos(ppos){} 13 bool operator < (const node b) const{ 14 return x < b.x; 15 } 16 }a[N]; 17 18 int n; 19 int ans[N]; 20 set <node> S; 21 set <node> :: iterator it,it1; 22 int cmp(node a,node b){ 23 return a.p>b.p; 24 } 25 26 int main(){ 27 scanf("%d",&n); 28 for (int i=1;i<=n;i++){ 29 scanf("%d %d",&a[i].x,&a[i].p); 30 a[i].pos=i; 31 } 32 sort(a+1,a+n+1,cmp); 33 ans[a[1].pos]=-1; 34 S.insert(a[1]); 35 node x,y; 36 for (int i=2;i<=n;i++){ 37 S.insert(a[i]); 38 it = S.find(a[i]); 39 it1=it; it1++; 40 if (it==S.begin()){ 41 it++; x=*it; 42 ans[a[i].pos]=x.pos; 43 } else 44 if (it1==S.end()){ 45 it--; x=*it; 46 ans[a[i].pos]=x.pos; 47 } else 48 { 49 it--; x=*it; it++; 50 it++; y=*it; it--; 51 if (a[i].x-x.x<y.x-a[i].x) ans[a[i].pos]=x.pos; 52 if (a[i].x-x.x>y.x-a[i].x) ans[a[i].pos]=y.pos; 53 if (a[i].x-x.x==y.x-a[i].x) 54 if (x.p>y.p) ans[a[i].pos]=x.pos; 55 else ans[a[i].pos]=y.pos; 56 } 57 } 58 for (int i=1;i<=n;i++) printf("%d ",ans[i]); printf("\n"); 59 }