程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> UVA 10041 Vitos Family (中位數)

UVA 10041 Vitos Family (中位數)

編輯:C++入門知識

  Problem C: Vito's family 

 

Background
The world-known gangster Vito Deadstone is moving to New York. He has a very big family there, all of them living in Lamafia Avenue. Since he will visit all his relatives very often, he is trying to find a house close to them.

Problem
Vito wants to minimize the total distance to all of them and has blackmailed you to write a program that solves his problem.

Input
The input consists of several test cases. The first line contains the number of test cases.
For each test case you will be given the integer number of relatives r ( 0 < r < 500) and the street numbers (also integers) where they live ( 0 < si < 30000 ). Note that several relatives could live in the same street number.


Output
For each test case your program must write the minimal sum of distances from the optimal Vito's house to each one of his relatives. The distance between two street numbers si and sj is dij= |si-sj|.

Sample Input
2
2 2 4
3 2 4 6
Sample Output
2
4題意:Vito有r個鄰居。。在一條街道上。每個鄰居有一個位置。 要求出Vito住的一個地方使得他到所有鄰居距離總和最短。
思路:求中位數。。其實也不用求到中位數。。只要把所有鄰居從小到大排序,分成兩邊。取最中間數就可以了。如果是偶數。就兩個隨便取一個就可以了。。具體原因自己想。


代碼:


 

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <algorithm>
using namespace std;

int t, r, s[505], mid, sum;

int main() {
    scanf("%d", &t);
    while (t --) {
	sum = 0;
	scanf("%d", &r);
	for (int i = 0; i < r; i ++)
	    scanf("%d", &s[i]);
	sort(s, s + r);
	mid = s[r / 2];
	for (int i = 0; i < r ; i ++) {
	    sum += abs(s[i] - mid);
	}
	printf("%d\n", sum);
    }
    return 0;
}

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved