您的位置:首页 > 其它

HDU 4311 4312 Meeting point 平面上的Manhattan距离和Chebyshev距离

2012-09-05 20:52 393 查看
题意:给定平面坐标上n(n<=100000)个点,然后在其中选一个,使得所有点到当前点的Manhattan距离和Chebyshev距离和最小。

平面上两点间的 Manhattan 距离为 |x1-x2| + |y1-y2|,平面上两点间的 Chebyshev距离为 max(|x1-x2|, |y1-y2|)。

题解:扫描线算法,对于Manhattan距离将x y方向坐标分开处理,分别求出当前坐标到其他坐标的x(y)距离和,然后扫描所有的点,二分确定位置更新答案;

对于原坐标系中两点间的Chebyshev距离,将坐标轴顺时针旋转45度,所有点的坐标值放大sqrt(2)倍所得到的新坐标系中的Manhattan距离的二分之一。

Sure原创,转载请注明出处。

Meeting point - 1

#include <iostream>
#include <cstdio>
#include <memory.h>
#include <algorithm>
#define MIN(a , b) ((a) < (b) ? (a) : (b))
using namespace std;
const __int64 oo = (~(0ULL) >> 1);
const int maxn = 100002;
struct P
{
__int64 x,y;
}po[maxn];
__int64 xx[maxn],yy[maxn],anx[maxn],any[maxn];
int n;

void read()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%I64d %I64d",&xx[i],&yy[i]);
po[i].x = xx[i];
po[i].y = yy[i];
}
sort(xx+1 , xx+n+1);
sort(yy+1 , yy+n+1);
return;
}

void make()
{
anx[1] = 0,any[1] = 0;
for(int i=2;i<=n;i++)
{
anx[1] += xx[i] - xx[1];
any[1] += yy[i] - yy[1];
}
for(int i=2;i<=n;i++)
{
anx[i] = anx[i-1] - (xx[i] - xx[i-1]) * (n - 2 * i + 2);
any[i] = any[i-1] - (yy[i] - yy[i-1]) * (n - 2 * i + 2);
}
return;
}

void solve()
{
make();
__int64 res = oo;
for(int i=1;i<=n;i++)
{
int idx = lower_bound(xx + 1 , xx + n + 1 , po[i].x) - xx;
int idy = lower_bound(yy + 1 , yy + n + 1 , po[i].y) - yy;
res = MIN(res , anx[idx] + any[idy]);
}
printf("%I64d\n",res);
return;
}

int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
read();
solve();
}
return 0;
}


Meeting point - 2

#include <iostream>
#include <cstdio>
#include <memory.h>
#include <algorithm>
#define MIN(a , b) ((a) < (b) ? (a) : (b))
using namespace std;
const __int64 oo = (~(0ULL) >> 1);
const int maxn = 100002;
struct P
{
__int64 x,y;
}po[maxn];
__int64 xx[maxn],yy[maxn],anx[maxn],any[maxn];
int n;

void read()
{
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%I64d %I64d",&xx[i],&yy[i]);
po[i].x = xx[i] - yy[i];
po[i].y = xx[i] + yy[i];
xx[i] = po[i].x;
yy[i] = po[i].y;
}
sort(xx+1 , xx+n+1);
sort(yy+1 , yy+n+1);
return;
}

void make()
{
anx[1] = 0,any[1] = 0;
for(int i=2;i<=n;i++)
{
anx[1] += xx[i] - xx[1];
any[1] += yy[i] - yy[1];
}
for(int i=2;i<=n;i++)
{
anx[i] = anx[i-1] - (xx[i] - xx[i-1]) * (n - 2 * i + 2);
any[i] = any[i-1] - (yy[i] - yy[i-1]) * (n - 2 * i + 2);
}
return;
}

void solve()
{
make();
__int64 res = oo;
for(int i=1;i<=n;i++)
{
int idx = lower_bound(xx + 1 , xx + n + 1 , po[i].x) - xx;
int idy = lower_bound(yy + 1 , yy + n + 1 , po[i].y) - yy;
res = MIN(res , anx[idx] + any[idy]);
}
printf("%I64d\n",res / 2);
return;
}

int main()
{
int cas;
scanf("%d",&cas);
while(cas--)
{
read();
solve();
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: