hdu 5992 Finding Hotels (kd-tree 裸题,查询)
题意:
有若干个(2E5)旅馆,分别给出旅馆的坐标和价格。有m个查询,每个查询给出一个人的位置(x0,y0),以及其能接受的最高价格。问在该人能接受的价格内,距离其最近的旅馆的坐标和价格是多少。
思路:
加了价格的限制其实无所谓,只要在更新的时候,先判一下价格就行了。
训练的时候不会kd-tree。。感觉有点可惜了。不然就6题了orz
/* ***********************************************
Author :111qqz
Created Time :2017年10月08日 星期日 18时43分38秒
File Name :5992.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define PB push_back
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N=2E5+7;
7int n,m;
8struct Point
9{
10 LL x,y;
11 int c;
12 int id;
13}p[N];
14bool dv[N]; //划分方式
15bool cmpx( const Point & p1, const Point &p2)
16{
17 return p1.x<p2.x;
18}
19bool cmpy(const Point &p1 ,const Point &p2)
20{
21 return p1.y<p2.y;
22}
23LL getDis( Point a, Point b)
24{
25 return (a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y);
26}
27void build ( int l,int r)
28{
29 if (l>r) return;
30 int mid = (l+r) >> 1;
31 int minx = min_element(p+l,p+r,cmpx)->x;
32 int miny = min_element(p+l,p+r,cmpy)->y;
33 int maxx = max_element(p+l,p+r,cmpx)->x;
34 int maxy = max_element(p+l,p+r,cmpy)->y;
35 dv[mid] = maxx-minx >= maxy-miny;
36 nth_element(p+l,p+mid,p+r+1,dv[mid]?cmpx:cmpy);
37 build(l,mid-1);
38 build(mid+1,r);
1}
2LL res,ansid;
3void query( int l,int r,Point a)
4{
5 if (l>r) return;
6 int mid = (l+r)>>1;
7 LL dis = getDis(a,p[mid]);
8 //printf("%lld %lld %lld %lld %lld\n",a.x,a.y,p[mid].x,p[mid].y,dis);
9 if (a.c>=p[mid].c)
10 {
11 if (dis<res) res = dis,ansid = mid;
12 else if (dis==res&&p[mid].id<p[ansid].id) ansid = mid;
13 }
14 LL d = dv[mid]?(a.x-p[mid].x):(a.y-p[mid].y);
15 int l1=l,r1=mid-1,l2=mid+1,r2=r;
16 if (d>0) swap(l1,l2),swap(r1,r2);
17 query(l1,r1,a); //左儿子
18 if (d*d<res) query(l2,r2,a);//如果与分界线相交,则也要查询右儿子。
19}
1int main()
2{
3 #ifndef ONLINE_JUDGE
4 freopen("./in.txt","r",stdin);
5 #endif
6 int T;
7 cin>>T;
8 while (T--)
9 {
10 scanf("%d%d",&n,&m);
11 for ( int i = 1 ; i <= n ; i++) {
12 scanf("%lld %lld %d",&p[i].x,&p[i].y,&p[i].c);
13 p[i].id = i;
14 }
15 build (1,n);
16 while (m--)
17 {
1 res = 1LL<<60;
2 Point p2;
3 scanf("%lld%lld%d",&p2.x,&p2.y,&p2.c);
4 query(1,n,p2);
5 printf("%lld %lld %d\n",p[ansid].x,p[ansid].y,p[ansid].c);
6 }
1 }
2 #ifndef ONLINE_JUDGE
3 fclose(stdin);
4 #endif
5 return 0;
6}