Algorithm Problem:Teams Forming

B. Teams Forming
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
There are n students in a university. The number of students is even. The i-th student has programming skill equal to ai.

The coach wants to form n2 teams. Each team should consist of exactly two students, and each student should belong to exactly one team. Two students can form a team only if their skills are equal (otherwise they cannot understand each other and cannot form a team).

Students can solve problems to increase their skill. One solved problem increases the skill by one.

The coach wants to know the minimum total number of problems students should solve to form exactly n2 teams (i.e. each pair of students should form a team). Your task is to find this number.

Input
The first line of the input contains one integer n (2≤n≤100) — the number of students. It is guaranteed that n is even.

The second line of the input contains n integers a1,a2,…,an (1≤ai≤100), where ai is the skill of the i-th student.

Output
Print one number — the minimum total number of problems students should solve to form exactly n2 teams.
Examples
input

6
5 10 2 3 14 5
input
2
1 100
output
99

My Answer Code:

/*
	Author:Albert Tesla Wizard
	Time:2020/11/1 17:31
*/
#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n,ans=0;
    cin>>n;
    vector<int>a(n);
    for(int i=0;i<n;i++)cin>>a[i];
    sort(a.begin(),a.end());
    for(int i=1;i<=n-1;i+=2)ans+=(a[i]-a[i-1]);
    cout<<ans<<'\n';
    return 0;
}

猜你喜欢

转载自blog.csdn.net/AlberTesla/article/details/109431493