B. BerSU Ball
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output
The Berland State University is hosting a ballroom dance in celebration of its 100500-th anniversary! n boys and m girls are already busy rehearsing waltz, minuet, polonaise and quadrille moves.
We know that several boy&girl pairs are going to be invited to the ball. However, the partners' dancing skill in each pair must differ by at most one.
For each boy, we know his dancing skills. Similarly, for each girl we know her dancing skills. Write a code that can determine the largest possible number of pairs that can be formed from n boys and m girls.
Input
The first line contains an integer n (1 ≤ n ≤ 100) — the number of boys. The second line contains sequence a1, a2, ..., an (1 ≤ ai ≤ 100), where ai is the i-th boy's dancing skill.
Similarly, the third line contains an integer m (1 ≤ m ≤ 100) — the number of girls. The fourth line contains sequence b1, b2, ..., bm (1 ≤ bj ≤ 100), where bj is the j-th girl's dancing skill.
Output
Print a single number — the required maximum possible number of pairs.
Examples
input
4 1 4 6 2 5 5 1 5 7 9
output
3
input
4 1 2 3 4 4 10 11 12 13
output
0
input
5 1 1 1 1 1 3 1 2 3
output
2
题目大意:
给出男女生人数 以及各自的舞蹈技能点数 两人点数相近(差值小于等于1)才可以搭档
求最多成对数
解题思路:
用数量小的序列去一个一个配对 可以的就将长序列中的那个人踢出配对循环(给个flag作为判断条件)
但是直接这样会出问题 虽然可以得到成对数 但却不是最大的成对数 因为 两个序列都是无序的
例如这组数据
3 6 3 4 3 4 5 2
6会去找5 3去找4 4只能去找2 但无法成对
如果将这两个序列排成有序的话
3 3 4 6 3 2 4 5
那么序列一中的数 会找到序列二中最小的且和他相近的人配对
这样就能优化配对方法 使得得到最大值
下面是代码
AC code:
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int Solve(int x[110],int y[110],int p,int q)
{
int flag[110]={0};
int ans = 0 ;
for(int i = 0 ; i < p ; i++)
{
for(int j = 0 ; j < q ; j++)
{
if(abs(x[i]-y[j])<=1)
{
if(flag[j]==0)
{
flag[j]=1;
ans++;
break;
}
}
}
}
return ans;
}
int main ()
{
int n, m;
int a[110], b[110];
cin >> n;
for(int i = 0 ; i < n ; i++) cin >> a[i];
cin >> m;
for(int i = 0 ; i < m ; i++) cin >> b[i];
sort(a,a+n);//要得到最优解(最大组队数) 先对各个序列排序 才能达到最优
sort(b,b+m);
if(n<m)
cout << Solve(a,b,n,m);
else cout << Solve(b,a,m,n);
return 0;
}