TZOJ 1689 Building A New Barn(求平面上有几个其它点求到n个点的曼哈顿距离最小)

描述

After scrimping and saving for years, Farmer John has decided to build a new barn. He wants the barn to be highly accessible, and he knows the coordinates of the grazing spots of all N (2 ≤ N ≤ 10,000 cows. Each grazing spot is at a point with integer coordinates (XiYi) (-10,000 ≤ Xi ≤ 10,000; -10,000 ≤ Yi ≤ 10,000). The hungry cows never graze in spots that are horizontally or vertically adjacent.

The barn must be placed at integer coordinates and cannot be on any cow's grazing spot. The inconvenience of the barn for any cow is given the Manhattan distance formula | X - Xi | + | Y - Yi|, where (XY) and (XiYi) are the coordinates of the barn and the cow's grazing spot, respectively. Where should the barn be constructed in order to minimize the sum of its inconvenience for all the cows?

输入

Line 1: A single integer: N 
Lines 2..N+1: Line i+1 contains two space-separated integers which are the grazing location (XiYi) of cow i

输出

Line 1: Two space-separated integers: the minimum inconvenience for the barn and the number of spots on which Farmer John can build the barn to achieve this minimum.

样例输入

4
1 -3
0 1
-2 1
1 -1

样例输出

10 4

提示

The minimum inconvenience is 10, and there are 4 spots that Farmer John can build the farm to achieve this: (0, -1), (0, 0), (1, 0), and (1, 1).
题意
给你n个二维平面上的点,求平面上有几个其它点到n个点的曼哈顿距离最小,并输出最小值
题解
曼哈顿距离∑ | X - Xi | + | Y - Yi|,X和Y互不影响可以单独考虑
分别为x和y排序,然后X和Y就是中位数
当中位数唯一:
1.n个点中存在(X,Y),判断(X,Y)上下左右四个点即可
2.否则,只有一个点(X,Y)
当中位数不唯一:
1.答案为(X1-X2)(Y1-Y2)矩形的大小-矩形中已经存在的点的个数
代码
 #include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std; const int maxn=;
int n;
struct p
{
int x,y;
}a[maxn];
bool cmp1(p a,p b){return a.x<b.x;}
bool cmp2(p a,p b){return a.y<b.y;}
bool check(int xx,int yy)
{
for(int i=;i<n;i++)if(a[i].x==xx&&a[i].y==yy)return ;
return ;
}
int sum(int xx,int yy)
{
int ans=;
for(int i=;i<n;i++)
ans+=abs(xx-a[i].x)+abs(yy-a[i].y);
return ans;
}
int dx[]={,,,-};
int dy[]={,-,,};
int main()
{
scanf("%d",&n);
for(int i=;i<n;i++)scanf("%d%d",&a[i].x,&a[i].y);
if(n%==)
{
int mid=n/;
sort(a,a+n,cmp1);
int xx=a[mid].x;
sort(a,a+n,cmp2);
int yy=a[mid].y;
if(check(xx,yy))printf("%d 1\n",sum(xx,yy));
else
{
int minn=1e9,ans=;
for(int i=;i<;i++)
{
int val=sum(xx+dx[i],yy+dy[i]);
if(val<minn)minn=val,ans=;
else if(val==minn)ans++;
}
printf("%d %d\n",minn,ans);
}
}
else
{
int mid=n/;
sort(a,a+n,cmp1);
int x1=a[mid-].x,x2=a[mid].x;
sort(a,a+n,cmp2);
int y1=a[mid-].y,y2=a[mid].y;
int ans=(x2-x1+)*(y2-y1+);
for(int i=;i<n;i++)
if(x1<=a[i].x&&a[i].x<=x2&&y1<=a[i].y&&a[i].y<=y2)
ans--;
printf("%d %d\n",sum(x1,y1),ans);
}
return ;
}
上一篇:HDU 4311 Meeting point-1 && HDU 4312 Meeting point-2


下一篇:hdu 1358 Period(kmp求一个串的重复子串)