Problem Description
There are N hotels all over the world. Each hotel has a location and a price. M guests want to find a hotel with an acceptable price and a minimum distance from their locations. The distances are measured in Euclidean metric.
Input
The first line is the number of test cases. For each test case, the first line contains two integers N (N ≤ 200000) and M (M ≤ 20000). Each of the following N lines describes a hotel with 3 integers x (1 ≤ x ≤ N), y (1 ≤ y ≤ N) and c (1 ≤ c ≤ N), in which x and y are the coordinates of the hotel, c is its price. It is guaranteed that each of the N hotels has distinct x, distinct y, and distinct c. Then each of the following M lines describes the query of a guest with 3 integers x (1 ≤ x ≤ N), y (1 ≤ y ≤ N) and c (1 ≤ c ≤ N), in which x and y are the coordinates of the guest, c is the maximum acceptable price of the guest.
Output
For each guests query, output the hotel that the price is acceptable and is nearest to the guests location. If there are multiple hotels with acceptable prices and minimum distances, output the first one.
Source
2016ACM/ICPC亚洲区青岛站-重现赛(感谢中国石油大学)
Solution
KD-tree裸题,记录每一个子树中最小的价格。暴力碾过去就好了。
#include<stdio.h>
#include<algorithm>
#include<cmath>
#define N 200002
using namespace std;
typedef long long ll;
int Judge,T,n,m,mn[N],lson[N],rson[N];
struct poi
{
int a[2],c,p;
inline void in(){scanf("%d%d%d",a,a+1,&c);}
inline void copy(const poi &b){a[0]=b.a[0];a[1]=b.a[1];c=b.c;p=b.p;}
friend bool operator < (const poi &a,const poi &b){return a.a[Judge]<b.a[Judge];}
}a[N],aim,ans;
int build(const int &l,const int &r)
{
if (r<l) return 0;
int mid=(l+r)>>1;
Judge^=1;
nth_element(a+l,a+mid,a+r+1);
mn[mid]=min(min(mn[lson[mid]=build(l,mid-1)],mn[rson[mid]=build(mid+1,r)]),a[mid].c);
Judge^=1;
return mid;
}
inline ll dis(const poi &a){return (ll)(a.a[0]-aim.a[0])*(a.a[0]-aim.a[0])+(ll)(a.a[1]-aim.a[1])*(a.a[1]-aim.a[1]);}
inline bool cmp(const poi &a,const poi &b)
{
ll d1=dis(a),d2=dis(b);
if (aim.c<b.c) return 1;
return d1==d2?a.p<b.p:d1<d2;
}
void find(const int &l,const int &r)
{
int mid=(l+r)>>1;
if (a[mid].c<=aim.c && cmp(a[mid],ans)) ans.copy(a[mid]);
Judge^=1;
if (aim.a[Judge]<=a[mid].a[Judge])
{
if (mn[lson[mid]]<=aim.c) find(l,mid-1);
if (mn[rson[mid]]<=aim.c && (aim.c<ans.c || a[mid].a[Judge]<=aim.a[Judge]+sqrt(dis(ans)))) find(mid+1,r);
}
else
{
if (mn[rson[mid]]<=aim.c) find(mid+1,r);
if (mn[lson[mid]]<=aim.c && (aim.c<ans.c || aim.a[Judge]<=a[mid].a[Judge]+sqrt(dis(ans)))) find(l,mid-1);
}
Judge^=1;
}
int main()
{
scanf("%d",&T);
mn[0]=233333333;
while (T--)
{
scanf("%d%d",&n,&m);
for (int i=1;i<=n;i++) a[i].in(),a[i].p=i;
build(1,n);
while (m--)
{
aim.in();ans.c=233333333;
find(1,n);
printf("%d %d %d\n",ans.a[0],ans.a[1],ans.c);
}
}
}