题目描述
某石油公司计划建造一条由东向西的主要输油管道。该管道要穿过一个有n口油井的油田。从每口油井都要有一条输油管道沿最短路径(或南或北)与主管道相连。如果给定n口油井的位置,及它们的x坐标(东西向)和y坐标(南北向),应如何确定主管道的最优位置,即使各油井到主管道之间的输油管道长度总和最小的位置?证明可规定时间内确定主管道的最优位置。
注:为方便铺设,要求主管道铺设在整数位置点
输入
第一行是油井数n(1<=n<=10000)
接下来n行是油井的位置,每行2个整数x和y(-10000<=x,y<=10000)
输出
只有一行
是油井到主管道之间的输油管道最小长度总和
样例输入 Copy
5 1 2 2 2 1 3 3 -2 3 3
样例输出 Copy
6
#include<iostream>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
int n;
int median;
cin >> n;
vector<pair<int, int>> wells(n);
int count = 0;
while (count < n)
{
cin >> wells[count].first >> wells[count].second;
count++;
}
sort(wells.begin(), wells.end(), [](pair<int, int>& a, pair<int, int>& b)
{
return a.second < b.second;
});
median= wells[n / 2].second;
int sum=0;
for (auto &well:wells)
{
sum += abs(well.second - median);
}
cout << sum << endl;
return 0;
}