There is an infinite integer grid at which N retired TJU-ACMers have their houses on. They decide to unite at a common meeting place, which is someone's house. From any given cell, only 4 adjacent cells are reachable in 1 unit of time.
Eg: (x,y) can be reached from (x-1,y), (x+1,y), (x, y-1), (x, y+1).
Finding a common meeting place which minimizes the sum of the travel time of all the retired TJU-ACMers.
For each test case, the first line is an integer n represents there are n retired TJU-ACMers. (0<n<=100000), the following n lines each contains two integers x, y coordinate of the i-th TJU-ACMer. (-10^9 <= x,y <= 10^9)
4 6 -4 -1 -1 -2 2 -4 0 2 0 3 5 -2 6 0 0 2 0 -5 -2 2 -2 -1 2 4 0 5 -5 1 -1 3 3 1 3 -1 1 -1 10 -1 -1 -3 2 -4 4 5 2 5 -4 3 -1 4 3 -1 -2 3 4 -2 2
26
20
20
56
In the first case, the meeting point is (-1,-2); the second is (0,0), the third is (3,1) and the last is (-2,2)
题意:给你一些点,找到一点使其他点到该点的曼哈顿距离最小,(曼哈顿距离是指只有垂直和竖直方向)
思路:直接暴力求解,遍历各个点,依次把他们作为所求点,再找最小值即可,data[i].x,data[i].y为第i个点的坐标。data[i].sum存储其他点到该点的曼哈顿距离,找最小值即可,那只要确定个点到该点的曼哈顿距离就行了
data[i].sum=(i-1)*data[i].x-(data[1].x~data[i-1].x累加)+(data[i+1].x~data[n].x累加)-(n-i)*data[i].x
这是水平方向的距离
竖直方向同理
然后找到最小值即可:
ac代码
#include <iostream> #include <cstdio> #include <algorithm> using namespace std; struct point { long long x; long long y; long long sum; }data[100001]; bool cmpx(point a,point b) { return a.x<b.x; } bool cmpy(point a,point b) { return a.y<b.y; } int main() { int t,d; scanf("%d",&t); while(t--) { scanf("%d",&d); for(int i=1;i<=d;i++) scanf("%lld%lld",&data[i].x,&data[i].y); sort(data+1,data+d+1,cmpx); long long sum1=0; for(int i=1;i<=d;i++) { data[i].sum=(i-1)*data[i].x-sum1; sum1+=data[i].x; } sum1=0; for(int i=d;i>=1;i--) { data[i].sum+=sum1-(d-i)*data[i].x; sum1+=data[i].x; } sort(data+1,data+d+1,cmpy); sum1=0; for(int i=1;i<=d;i++) { data[i].sum+=(i-1)*data[i].y-sum1; sum1+=data[i].y; } sum1=0; for(int i=d;i>=1;i--) { data[i].sum+=sum1-(d-i)*data[i].y; sum1+=data[i].y; } long long ans=data[1].sum; for(int i=2;i<=d;i++) ans=min(ans,data[i].sum); printf("%lld\n",ans); } return 0; }
当时做这道题时一直不过,后来才发现犯了个zz的错误,在结构体外面定义了一个sum[100]储存结果但是忽略了一旦排序后,就不再对应原来那个数的储存值了