In: Computer Science
Objective:
The purpose of this programming assignment is to practice using STL containers.
This problem is selected from the online contest problem archive (Links to an external site.), which is used mostly by college students world wide to challenge their programming ability and to prepare themselves for attending programming contests such as the prestige ACM International Collegiate Programming Contest (Links to an external site.). For your convenience, I copied the description of the problem below with my note on the I/O and a sample executable.
Background
The world-known gangster Vito Deadstone is moving to New York. He has a very big family there, all of them live on 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
Note: If you input the above sample data from
the keyboard, the output will be printed on your screen right after
each test case.
Another sample input and output:
input
1
10 2 12 23 10 3 40 20 19 4 15
output
86
Please find your solution below and if any doubt comment and do upvote.
CODE:
#include<bits/stdc++.h>
using namespace std;
int main()
{
//variable for testcase
int t;
cin>>t;
int st;
while(t--)
{
//vector to store street number
vector<int>v;
//variable for number of street
int n;
cin>>n;
//take input
for(int i=0;i<n;i++)
{
cin>>st;
v.push_back(st);
}
sort(v.begin(),v.end());
//find mid
int mid=v[v.size()/2];
long int totalDistance=0;
//find total distance
for(int i=0;i<v.size();i++)
{
totalDistance=totalDistance+abs(mid-v[i]);
}
cout<<totalDistance<<endl;
}
return 0;
}
OUTPUT: