输油管道问题

输油管道问题

Time Limit:1000MS  Memory Limit:65536K
Total Submit:181 Accepted:100

Description

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

Input

输入由多组测试数据组成。
每组测试数据输入的第1 行是油井数n,1≤n≤10000。接下来n 行是油井的位置,每行2个整数x和y,-10000≤x,y≤10000。

Output

对应每组输入,输出的第1 行中的数是油井到主管道之间的输油管道最小长度总和。

Sample Input

5
1 2
2 2
1 3
3 -2
3 3

 

Sample Output

6

 

源码:

 

#include <iostream>
#include 
<algorithm>
using namespace std;

const int MAX_SIZE = 10002;

bool cmp(int a, int b)
{
    
if(a < b)
        
return true;
    
else
        
return false;
}


int cal(int str[], int n)
{
    
int sum = 0, mid = str[n / 2];
    
for(int i = 0; i < n; i++)
        sum 
+= abs(str[i] - mid);
    
return sum;
}

int main()
{
    
int x,y[MAX_SIZE];
    
int i, n;
    
while(cin>>n)
    
{
        
for(i = 0; i < n; i++)
            scanf(
"%d%d",&x,y + i);
        sort(y, y 
+ n, cmp);
        printf(
"%d\n",cal(y,n));
    }

    
return 0;
}

posted on 2009-03-19 20:26  Xredman  阅读(1282)  评论(1编辑  收藏  举报

导航