SSL_1125【集合】

集合

题目

给定两个集合A、B,集合内的任一元素x满足1 ≤ x ≤ 109,并且每个集合的元素个数不大于105。我们希望求出A、B之间的关系。
任 务 :给定两个集合的描述,判断它们满足下列关系的哪一种:
A是B的一个真子集,输出“A is a proper subset of B”
B是A的一个真子集,输出“B is a proper subset of A”
A和B是同一个集合,输出“A equals B”
A和B的交集为空,输出“A and B are disjoint”
上述情况都不是,输出“I’m confused!”

Input

输入有两行,分别表示两个集合,每行的第一个整数为这个集合的元素个数(至少一个),然后紧跟着这个集合的元素(均为不同的正整数)

Output

只有一行,就是A、B的关系。

Sample Input

2 55 27
2 55 27
3 9 24 1995
2 9 24
3 1 2 3
4 1 2 3 4
3 1 2 3
3 4 5 6
2 1 2
2 2 3

Sample Output

A equals B
B is a proper subset of A
A is a proper subset of B
A and B are disjoint
I'm confused!

解析

样例充足
这道题其实就是哈希的练手题,条件如下:
设哈希后得到B集与A集共有的个数为sum
sum=n&&n=m 相等(别问为什么不是两个等号,系统会判定为标记文本)
sum=n&&n<m A是B的子集
sum=n&&n>m B是A的子集
sum==0 AB无交集
剩下的都是最后一种
讲完了?不,还有一种
sort+二分查找
附上代码:

code(Hash):

#include<cstdio>
#define mod 1000007
using namespace std;
int n,m,a[mod],s=0,t;
int h(int x)
{
    
    
	return x%mod;
}
int wh(int x)
{
    
    
	int q=h(x),i=0;
	while(i<mod&&a[(q+i)%mod]&&a[(q+i)%mod]!=x)++i;
	return (q+i)%mod;
}
int main()
{
    
    
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&t),a[wh(t)]=t;
	scanf("%d",&m);
	for(int i=1;i<=m;i++)
	{
    
    
		scanf("%d",&t);
		if(a[wh(t)]==t)s++;
	}
	if(s==n&&n==m)printf("A equals B");
	else if(s==m&&n>m)printf("B is a proper subset of A");
	else if(s==n&&n<m)printf("A is a proper subset of B");
	else if(s==0)printf("A and B are disjoint");
	else printf("I'm confused!");
	return 0;
}

code(sort+二分查找):

#include<algorithm>
#include<cstdio>
using namespace std;
int n,m,a[100010],b[100010],tot,sum=0,t=0;
int main()
{
    
    
	scanf("%d",&n);
	for(int i=1;i<=n;i++)scanf("%d",&a[i]);
	scanf("%d",&m);
	for(int i=1;i<=m;i++)scanf("%d",&b[i]);
	if(m<n)
	{
    
    
		swap(n,m);
		++t;
		for(int i=1;i<=m;i++)swap(a[i],b[i]);
	}
//	sort(a+1,a+n+1);
	//这句是打的时候多写的,后来删掉了,但是删后更慢了……
	sort(b+1,b+m+1);
	for(int i=1;i<=n;i++)
	{
    
    
		tot=lower_bound(b+1,b+m+1,a[i])-b;
		if(b[tot]==a[i])sum++;
	}
	if(sum==n)
	{
    
    
		if(n==m)printf("A equals B");
		else if(t)printf("B is a proper subset of A");
		else printf("A is a proper subset of B");
	}
	else if(!sum)printf("A and B are disjoint");
	else printf("I'm confused!");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhanglili1597895/article/details/112970442
SSL
今日推荐