B. BERSU BALL(双指针)

http://www.yyycode.cn/index.php/2020/05/18/b-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 a 1, a 2, …, a n (1 ≤ a i ≤ 100), where a i 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 b 1, b 2, …, b m (1 ≤ b j ≤ 100), where b j is the j-th girl’s dancing skill.Output

Print a single number — the required maximum possible number of pairs.ExamplesinputCopy

4
1 4 6 2
5
5 1 5 7 9

outputCopy

3

inputCopy

4
1 2 3 4
4
10 11 12 13

outputCopy

0

inputCopy

5
1 1 1 1 1
3
1 2 3

outputCopy

2

题意:

有n个男孩和m个女孩

我们知道有几对男女要被邀请参加舞会。然而,每一对舞伴的舞技最多只能相差一个。

对于每个男孩,我们都知道他的舞蹈技巧。同样,对于每个女孩,我们都知道她的舞蹈技巧。编写一个代码,可以确定n个男孩和m个女孩可能形成的最大对数。


思路:数据小可以暴力O(n^2),但是如果真的出这个题不会让你n^2过的

对两个都进行排序,两段序列,男的那段用i指针维护,女的那段用j指针维护,如果出现了满足条件的,就res++,i++;j++;

如果说男的舞技术比女的多,女的指针j++; j指针往前走使差距变小

不然的话男的指针i++;

#include<iostream>
#include<vector>
#include<queue>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1e5;
typedef long long LL;
LL a[maxn];
LL b[maxn]; 
int main(void)
{
	LL n,m;cin>>n;
	for(LL i=1;i<=n;i++)
		cin>>a[i];
	cin>>m;	
	for(LL j=1;j<=m;j++)
		cin>>b[j];
	sort(a+1,a+1+n);sort(b+1,b+1+m);
	LL res=0;
	for(LL i=1,j=1;i<=n&&j<=m;)
	{
		if(abs(a[i]-b[j])<=1)
		{
			res++;i++;j++;
		}
		else if(a[i]>b[j])
		{
			j++;
		}
		else i++;
	}	
	cout<<res<<endl;
return 0;
}

猜你喜欢

转载自blog.csdn.net/zstuyyyyccccbbbb/article/details/106201548