Oil pipeline problems

Source: Internet
Author: User

Description

An oil company plans to build a main oil pipeline from east to west. The pipeline needs to pass through an oil field with N wells. Each well must have an oil pipeline along the shortest path (or south or north) connected to the main pipeline. How to determine the optimal position of the main pipeline if n wells are given, that is, their X coordinates (East-West) and Y coordinates (north-south direction, even if the total length of the oil pipeline from each well to the main pipeline is the smallest position? It is proved that the optimal position of the main pipe can be determined in linear time.
Programming task:
Given the location of N wells, the minimum length of the oil pipeline between each well and the main pipeline is calculated by programming.

Input

The number of wells in the input data is N, 1 <= n <= 1st. The next n rows are the locations of the wells. Each row has two integers x and y,-10000 <= X, Y <= 10000.

Output

When the program ends, the computing result is output. The number in the second row is the sum of the minimum length of the oil pipeline between the oil well and the main pipeline.

Sample Input

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

Sample output

6

Train of Thought: According to the question, the shortest problem is only related to the Y axis. First, determine the most position of the main pipe. Take this seat and subtract other positions from the shortest path.

Code:

#include<iostream>#include<algorithm>#include<cmath>using namespace std;int a[10000];int main(){    int n,q,p,c;    while(cin>>n)    {        int sum=0;        for(int i=0;i<n;i++)        {            cin>>q>>p;            a[i]=p;        }        sort(a,a+n);        c=a[n/2];        for(int i=0;i<n;i++)        sum+=abs(c-a[i]);        cout<<sum<<endl;    }    return 0;}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.