UVA 10041 Vito ' s Family

Source: Internet
Author: User

Original question:
The World-known gangster Vito Deadstone is moving to New York. He has a very big family there and all of them living in Lamafia Avenue. Since He'll visit all his relatives very often, he's trying to find a house close to them. Vito wants to minimize the total distance to all of the them and have blackmailed you to write a program that solves his proble M.
Input
The input consists of several test cases. The first line contains the number of test cases.
For each test case you'll be given the integer number of relatives R (0 < R < $) and the street
Numbers (also integers) s1, s2, ..., si, ..., sr 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 the his relatives. The distance between street numbers si and sj is Dij = |SI−SJ |.
Sample Input
2
2 2 4
3 2 4 6
Sample Output
2
4
English:
Give you a bunch of dots on a one-dimensional axis, and let you find a point that makes this point the distance and smallest of all points. Output and ready

#include <bits/stdc++.h>
using namespace std;

int main ()
{
    Ios::sync_with_stdio (false);
    int n,t;
    int a[501];
    cin>>t;
    while (t--)
    {
        cin>>n;
        memset (A,0,sizeof (a));
        for (int i=1;i<=n;i++)
            cin>>a[i];
        Sort (a+1,a+1+n);
        int ans=0;
        if (n%2)
        {for
            (int i=1;i<=n;i++)
                ans+=abs (a[i]-a[n/2+1]);
        }
        else
        {
            int tmp=0;
            for (int i=1;i<=n;i++)
            {
                ans+=abs (A[I]-A[N/2]);
                Tmp+=abs (a[i]-a[n/2+1]);
            }
            Ans=min (ans,tmp);
        }
        cout<<ans<<endl;
    }
    return 0;
}

Answer:
Super simple problem, find the median can be.

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.