算法题:输油管道问题 - 贪心

背景

想念car的GF,car就出了道水题!

描述

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

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

格式

输入格式

输入第1行是油井数n,1≤n≤10000。

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

输出格式

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

样例1

样例输入1

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

样例输出1

6

限制

各个测试点1s

提示

各个测试点1s

解题思路:

最南和最北的油井,到输油管道的管道长度最小值为它们南北坐标之差。

(ps:东西坐标位置不用考虑,只需要考虑南北)

我的解答:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;

class Main
{
    public static void main(String[] argv)
    {
        try {
            InputStreamReader inputStream = new InputStreamReader(System.in);
            BufferedReader buffer = new BufferedReader(inputStream);

            int n = Integer.parseInt(buffer.readLine());
            ArrayList<Integer> pointYList = new ArrayList<Integer>();
            for (int i = 1; i <= n; i++) {
                String[] pointStr = buffer.readLine().split(" ");
                pointYList.add(new Integer(pointStr[1]));
            }
            int totalLen = 0;
            Collections.sort(pointYList);
            while (true) {
                if (pointYList.size() >= 2) {
                    totalLen += pointYList.remove(pointYList.size() - 1) - pointYList.remove(0);
                } else {
                    break;
                }
            }
            System.out.println(totalLen);
        } catch (Exception ex) {
            System.out.println("Error:" + ex.getMessage());
        }
    }
}


猜你喜欢

转载自blog.csdn.net/loophome/article/details/79292445