题目链接:
http://codeforces.com/problemset/problem/779/A
In Berland each high school student is characterized by academic performance — integer value between 1 and 5.
In high school 0xFF there are two groups of pupils: the group A and the group B. Each group consists of exactly nstudents. An academic performance of each student is known — integer value between 1 and 5.
The school director wants to redistribute students between groups so that each of the two groups has the same number of students whose academic performance is equal to 1, the same number of students whose academic performance is 2 and so on. In other words, the purpose of the school director is to change the composition of groups, so that for each value of academic performance the numbers of students in both groups are equal.
To achieve this, there is a plan to produce a series of exchanges of students between groups. During the single exchange the director selects one student from the class A and one student of class B. After that, they both change their groups.
Print the least number of exchanges, in order to achieve the desired equal numbers of students for each academic performance.
The first line of the input contains integer number n (1 ≤ n ≤ 100) — number of students in both groups.
The second line contains sequence of integer numbers a1, a2, ..., an (1 ≤ ai ≤ 5), where ai is academic performance of the i-th student of the group A.
The third line contains sequence of integer numbers b1, b2, ..., bn (1 ≤ bi ≤ 5), where bi is academic performance of the i-th student of the group B.
Print the required minimum number of exchanges or -1, if the desired distribution of students can not be obtained.
4 5 4 4 4 5 5 4 5
1
6 1 1 1 1 1 1 5 5 5 5 5 5
3
1 5 3
-1
9 3 2 5 5 2 3 3 3 2 4 1 4 1 1 2 4 4 1
4
题目大意:
第一行输入一个整数n,第二行输入n个数(1-5),第三行输入n个数(1-5)。每次从第二行的数中选出来一个数字 与 第三行的数字进行交换,题目要求计算最少交换几次能够使得两组数中每个不同数字的个数相等。
解题思路:
分别用两个map容器(A,B)保存两组数中每个数字出现的次数,然后计算第一组数中每个数字出现次数 与 第二组数中对应数字的出现次数 的差值的绝对数值 除以二 。然后计算出的最终结果除以2 。如果不知道原因的话,就按照下面的代码,举一组测试数据试试即可。
代码:
#include<iostream>
#include<cmath>
#include<map>
using namespace std;
int main()
{
int n,s;
cin>>n;
map<int,int>A;
map<int,int>B;
for(int i=0;i<=n-1;i++)
{
cin>>s;
A[s]++;
}
for(int i=0;i<=n-1;i++)
{
cin>>s;
B[s]++;
}
int ans=0;
for(int i=1;i<=5;i++)
{
if((A[i]+B[i])%2!=0) //是奇数说明不能够均分,直接输出-1
{
cout<<-1<<endl;
return 0;
}
ans=ans+abs(A[i]-B[i])/2;
}
cout<<ans/2<<endl;
return 0;
}