Codeforces489B(题解)

这篇博客讨论了一道编程竞赛题目,涉及到在给定男生和女生舞蹈技能的情况下,如何通过排序优化方法找到最大数量的配对。题目要求男女舞伴之间的技能差异不超过1。博主提供了一个AC代码示例,通过排序两个序列并进行匹配,从而实现最大配对数。这种方法适用于处理无序数据,确保找到最优解。
摘要由CSDN通过智能技术生成

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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值