Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4995
The position Xi and VI are given on a one-dimensional coordinate axis. For M queries, the index Qi is given each time, and the Qi from the array subscript is obtained (starting from 1) the nearest K points are computed from the new value indicated by the subscript, that is, the sum of values equal to k recent points/K. If there are multiple nearest K points, select the group before the coordinate value.
Simulation questions. First, sort the positions from small to large, and then find the K nearest points of each point. The nearest point is determined by the distance between XI and the current xpos. If you find that the XL on the left is closer than the XR on the right to XI, select the left.
This code is made by scholars, who think they understand it, write it back and forth, and modify it many times before success ~~~
1 # include <iostream> 2 # include <cstdio> 3 # include <cstdlib> 4 # include <cstring> 5 # include <algorithm> 6 # include <vector> 7 using namespace std; 8 9 typedef _ int64 ll; 10 const int maxn = 1e5 + 5; 11 double VI [maxn]; 12 vector <int> G [maxn]; 13 int n, m, k; 14 15 struct node16 {17 int ID, XI; 18} Point [maxn]; 19 20 int CMP (const node & A, const node & B) 21 {22 return. xi <B. XI; 23} 24 25 bool judge (in T POs, int L, int R) 26 {27 if (r> N) 28 return true; 29 If (L <= 0) 30 return false; 31 if (point [POS]. xi-point [l]. xi! = Point [R]. xi-point [POS]. xi) // if the distance from the two sides is different, select the 32 return point [POS] point with a smaller distance value. xi-point [l]. xi <point [R]. xi-point [POS]. XI; 33 return point [l]. ID <point [R]. ID; // if the distance value from both sides is the same, select the 34} 35 36 void get_knn (int pos) with a small coordinate value) // obtain the latest K points of each point which are 37 {38 int id = point [POS]. ID; 39 int L = pos-1, R = POS + 1; 40 for (INT I = 0; I <K; I ++) 41 {42 if (Judge (Pos, L, R) 43g [ID]. push_back (point [l --]. ID); 44 else45 G [ID]. push_back (point [R ++]. ID); 46} 47} 48 49 int main () 50 {51 int t; 52 while (scanf ("% d", & T )! = EOF) 53 {54 while (t --) 55 {56 scanf ("% d", & N, & M, & K ); 57 for (INT I = 1; I <= N; I ++) 58 {59 scanf ("% d % lf", & point [I]. XI, & VI [I]); 60 point [I]. id = I; 61} 62 sort (point + 1, point + 1 + N, CMP); 63 for (INT I = 1; I <= N; I ++) 64 get_knn (I); 65 int ask; 66 double ans = 0; 67 for (INT I = 0; I <m; I ++) 68 {69 scanf ("% d", & ask); 70 double sum = 0; 71 for (Int J = 0; j <G [ask]. size (); j ++) 72 Sum + = VI [G [ask] [J]; 73 VI [ask] = sum/K; 74 ans + = VI [ask]; 75} 76 printf ("%. 6lf \ n ", ANS); 77 for (Int J = 1; j <= N; j ++) 78g [J]. clear (); 79} 80} 81 return 0; 82}
View code
Bestcoder9 1003 revenge of KNN (HDU 4995) solution report