7. 输油管道问题

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

编程任务:

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

输入格式

由文件input.txt提供输入数据。

文件的第1行是油井数n,1≤n≤10000。

接下来n行是油井的位置,每行2个整数x和y,-10000≤x,y≤10000。

输出格式

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

样例输入

5

1 2

2 2

1 3

3 -2

3 3

样例输出

6

 

思路:

所述问题可表述为求平面上的一条直线到若干点的最短路径。确定该直线的位置:只要该条直线处在所有点的中间位置就能保证最后的距离最短。若油井个数为n,则n为奇数,则取油井位置y坐标的中位数(n-1)/2;n为偶数,则取油井位置y坐标的下中位数和上中位数之间的任意一个数即可。

Code:

#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
#include<cstdlib>
#include<cmath> 
using namespace std;
int n;
vector<int> a;

int main() {
    FILE *fp, *out;
    if((fp = fopen("input.txt","a+")) == NULL) {
        cout << "Open file failed!";
        exit(1);
    }
    char c;
    fscanf(fp, "%d", &n);
    while(!feof(fp)){
        int x, y;
        fscanf(fp, "%d %d", &x,&y);
        a.push_back(y);
    }
    sort(a.begin(), a.end());
    int dis = 0;
    if (a[0] == a[n-1]) dis = 0;
    else {
        for (int i = 0; i < n/2; i++)
            dis += abs(a[i] - a[n-1-i]);
    }
    out = fopen("out.txt","w");
    fprintf(out, "最小长度为:%d",dis);  
    cout << dis;
    return 0;
}
原文地址:https://www.cnblogs.com/astonc/p/11705203.html