zoukankan      html  css  js  c++  java
  • UVa 10041 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

    有一个人住在纽约,现在他有r个亲戚,这个人经常会去所有的亲戚家,现在他想找到一个房子,使得每一次他去访问所有的亲戚时候走的路是最短的,输出这个最小值。

    想了半天以为很麻烦,结果就是一个求中位数的题。
    C语言代码如下:

    #include<stdio.h>
    #include<math.h>
    int main()
    {
    	int n,a[505],t,j,temp;
    	int sum;
    	scanf("%d",&n);
    	while(n--)
    	{
    		int i=0;
    		scanf("%d",&t);
    		for(i=0;i<t;i++)
    		{
    			scanf(" %d",&a[i]);
    		}
    		for(i=0;i<t;i++)
    			for(j=0;j<t-i-1;j++)
    				if(a[j]>a[j+1])
    				{
    					temp=a[j];
    					a[j]=a[j+1];
    					a[j+1]=temp;
    				}
    		sum=0;
    		temp=a[t/2];
    			for(i=0;i<t;i++)
    				sum+=abs(a[i]-temp);
    		printf("%d
    ",sum);
    	}
    	return 0;
    }
    
  • 相关阅读:
    composer国内镜像配置
    composer.json和composer.lock作用
    工厂模式(描述语言PHP)
    PHP后期静态绑定
    js事件冒泡和事件捕获
    去帮助别人,并接受别人的帮助
    平静,问题本身也是问题
    总是被欲望折磨的我
    习惯产生力量
    秦岭野生动物园
  • 原文地址:https://www.cnblogs.com/cnsec/p/11830693.html
Copyright © 2011-2022 走看看