问题 F: 深入浅出学算法014-输油管道问题

题目描述

某石油公司计划建造一条由东向西的主要输油管道。该管道要穿过一个有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;
}

  • 9
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值