BerSU Ball------贪心

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

题意

一场交谊舞,有n个男孩和m个女孩,一男一女组成一组,然而,每对舞伴的舞蹈技能最多只能相差一分。我们知道每个男孩和女孩的舞技是多少,问:n个男孩和m个女孩可以形成的最大的组。

解题思路

一道思路比较简单的题,看到这道题,我的第一想法就是先确定一个男孩,然后在女生中寻找符合条件的,有符合的条件的,就把这一组去掉,继续下一个男孩;如果没有,直接下一个男孩。为了方便代码实现,可以先对两个数组排序,再遍历即可

代码实现:

#include<iostream>
#include<algorithm>
using namespace std;
const int N = 1e3 + 10;
int a[N],b[N];
int main()
{
	int m,w;
	cin >> m;
	for (int i = 0; i < m; i++)
		cin >> a[i];
	cin >> w;
	for (int i = 0; i < w; i++)
		cin >> b[i];
	sort(a, a + m);//男孩排序
	sort(b, b + w);//女孩排序
	int k = 0,ans=0;
	for (int i = 0; i < m; i++)//遍历男孩
	{
		for (int j =k ; j < w; j++)//遍历女孩
		{
			if (b[j] == a[i] || b[j] == (a[i] - 1) || b[j] == (a[i] + 1))
			//判断是否有符合的
			{
				ans++;
				k = j + 1;
				break;
			}
			else
				continue;
		}
	}
	cout << ans << endl;
	return 0;
}
发布了22 篇原创文章 · 获赞 25 · 访问量 2208

猜你喜欢

转载自blog.csdn.net/SDAU_LGX/article/details/104930110