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;}