【a202】&&【9208】输油管道问题

Time Limit: 10 second

Memory Limit: 2 MB

问题描述

某石油公司计划建造一条由东向西的主输油管道。该管道要穿过一个有n 口油井的油 田。从每口油井都要有一条输油管道沿最短路经(或南或北)与主管道相连。如果给定n口油 井的位置,即它们的x 坐标(东西向)和y 坐标(南北向),应如何确定主管道的最优位置, 即使各油井到主管道之间的输油管道长度总和最小的位置?证明可在线性时间内确定主管道 的最优位置。 编程任务:

给定n 口油井的位置,编程计算各油井到主管道之间的输油管道最小长度总和。

Input

由文件input.txt 提供输入数据。文件的第1 行是油井数n,1≤n≤10000。接下来n 行是 油井的位置,每行2个整数x和y,-10000≤x,y≤10000。

Output

程序运行结束时,将计算结果输出到文件output.txt 中。文件的第1 行中的数是油井到 主管道之间的输油管道最小长度总和。

Sample Input

5

1 2

2 2

1 3

3 -2

3 3

Sample Output

6

【题解】



把所有的点按照y轴升序排;

然后取中位数(n+1)/2;

这个下标作为中位数d;然后把所有的点的纵坐标减去该d的绝对值累加到答案里就是最终答案了;



【完整代码】

#include <cstdio>
#include <algorithm> using namespace std; const int MAXN = 1e4+100; struct abc
{
int x,y;
}; int n;
abc a[MAXN]; bool cmp(abc a,abc b)
{
return a.y < b.y;
} int main()
{
//freopen("F:\\rush.txt","r",stdin);
scanf("%d",&n);
for (int i = 1;i <= n;i++)
scanf("%d%d",&a[i].x,&a[i].y);
sort(a+1,a+1+n,cmp);
int mid = (n+1)/2;
int ans = 0;
for (int i = 1;i <= n;i++)
ans += abs(a[i].y-a[mid].y);
printf("%d\n",ans);
return 0;
}