Codeforces Round #375 (Div. 2)A. The New Year: Mee
A. The New Year: Meeting Friends
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
There are three friend living on the straight line Ox in Lineland. The first friend lives at the point x1, the second friend lives at the point x2, and the third friend lives at the point x3. They plan to celebrate the New Year together, so they need to meet at one point. What is the minimum total distance they have to travel in order to meet at some point and celebrate the New Year?
It's guaranteed that the optimal answer is always integer.
Input
The first line of the input contains three distinct integers x1, x2 and x3 (1 ≤ x1, x2, x3 ≤ 100) — the coordinates of the houses of the first, the second and the third friends respectively.
Output
Print one integer — the minimum total distance the friends need to travel in order to meet together.
Examples
Input
7 1 4
Output
6
Input
30 20 10
Output
20
Note
In the first sample, friends should meet at the point 4. Thus, the first friend has to travel the distance of 3 (from the point 7 to the point 4), the second friend also has to travel the distance of 3 (from the point 1 to the point 4), while the third friend should not go anywhere because he lives at the point 4.
____________________
题意:给定a,b,c三个点,在数轴上找出一点p使他们距离之和sum最小,并输出最小的距离之和sum。
一开始直觉感觉是三个数平均数,交上去Wrong Answer on test 3 (test3是 1 4 100 ) 。
于是写了个暴力过了(毕竟答案肯定是整数,数据范围又小的可怜):
#include<iostream>
#include<cmath>
//#include<cstdlib>
using namespace std ;
int main()
{
 int a,b,c;
 int min = 101 ;
 cin >> a >> b >> c ;
 int temp = 0 ;
 for ( int i = 1 ; i <= 100 ; i++ )
 {
  temp = abs( a - i ) + abs ( b - i ) + abs( c - i );
  if(temp < min ) min = temp ;
 }
 cout << min << endl ;
 return 0 ; 
 
}
————
但我认为该题有数学方法并且可以推广,不需要写这么不优雅的暴力。
将该题推广如下:
在数轴上给定n个点,找一点p使p到各点距离之和最小。
——
经过一番讨论,发现p是n个点的中位数。
修改代码如下:
#include<iostream>
#include<cmath>
using namespace std ;
void swap( int &a , int &b)
{
 int temp ;
 temp = a ;
 a = b ;
 b = temp ;
}
int main()
{
 int a,b,c;
 cin >> a >> b >> c ;
 if( a > b ) swap(a,b);
 if(a > c ) swap(a,c);
 if( b>c) swap(b,c);
 cout << abs(a-b)+abs(c-b) << endl ;
  
 return 0 ; 
 
}
![]()
————————
对于n个点的证明:
假设p点不是那个点的中位数,则p点左边有m个数,右边有n个数(m≠n) 。
那么如果将p点向左移动d(但没有使p两边数的个数发生改变),则左边距离减少md,右边增加距离nd。右边移动同理。
因此,当p点左右两边数的个数不一样的时候,不是最优解。
所以p是中位数。(这里貌似不太严谨啊)
如果n是奇数,则p = (n + 1 ) /2
如果n是偶数,则p是在 ( n/2 , n/2 + 1 ) 上任意一点。
                    
                
                
            
        
浙公网安备 33010602011771号