标签:
Time Limit: 16000/8000 MS (Java/Others) Memory Limit: 98304/98304 K (Java/Others)
Total Submission(s): 3285 Accepted Submission(s): 1201
1 #include <algorithm> 2 #include <iostream> 3 #include <cstring> 4 #include <cstdio> 5 #include <queue> 6 using namespace std; 7 const int maxn=200010; 8 int cmpNo,K; 9 struct Node{ 10 int x[10],l,r,id; 11 bool operator <(const Node &b)const{ 12 return x[cmpNo]<b.x[cmpNo]; 13 } 14 }; 15 16 long long Dis(const Node &a,const Node &b){ 17 long long ret=0; 18 for(int i=0;i<K;i++) 19 ret+=(a.x[i]-b.x[i])*(a.x[i]-b.x[i]); 20 return ret; 21 } 22 23 Node p[maxn]; 24 25 int Build(int l,int r,int d){ 26 if(l>r)return 0; 27 cmpNo=d; 28 int mid=l+r>>1; 29 nth_element(p+l,p+mid,p+r+1); 30 p[mid].l=Build(l,mid-1,(d+1)%K); 31 p[mid].r=Build(mid+1,r,(d+1)%K); 32 return mid; 33 } 34 35 priority_queue<pair<long long,int> >q; 36 void Kth(int l,int r,Node tar,int k,int d){ 37 if(l>r)return; 38 int mid=l+r>>1; 39 pair<long long,int>v=make_pair(Dis(p[mid],tar),p[mid].id); 40 if(q.size()==k&&v<q.top())q.pop(); 41 if(q.size()<k)q.push(v); 42 long long t=tar.x[d]-p[mid].x[d]; 43 if(t<=0){ 44 Kth(l,mid-1,tar,k,(d+1)%K); 45 if(q.top().first>t*t) 46 Kth(mid+1,r,tar,k,(d+1)%K); 47 } 48 else{ 49 Kth(mid+1,r,tar,k,(d+1)%K); 50 if(q.top().first>t*t) 51 Kth(l,mid-1,tar,k,(d+1)%K); 52 } 53 } 54 int k,ans[20]; 55 Node a[maxn]; 56 int main(){ 57 int n; 58 while(scanf("%d%d",&n,&K)!=EOF){ 59 for(int id=1;id<=n;id++){ 60 for(int i=0;i<K;i++) 61 scanf("%d",&p[id].x[i]); 62 p[id].id=id; 63 a[id]=p[id]; 64 } 65 Build(1,n,0); 66 int Q; 67 scanf("%d",&Q); 68 Node tar; 69 while(Q--){ 70 for(int i=0;i<K;i++) 71 scanf("%d",&tar.x[i]); 72 scanf("%d",&k); 73 Kth(1,n,tar,k,0); 74 printf("the closest %d points are:\n",k); 75 int tot=0; 76 while(!q.empty()){ 77 int id=(q.top()).second;q.pop(); 78 ans[tot++]=id; 79 } 80 for(int i=tot-1;i>=0;i--) 81 for(int j=0;j<K;j++) 82 printf("%d%c",a[ans[i]].x[j],j==K-1?‘\n‘:‘ ‘); 83 } 84 } 85 return 0; 86 }
数据结构(KD树):HDU 4347 The Closest M Points
标签:
原文地址:http://www.cnblogs.com/TenderRun/p/5574384.html