【SSL】1125集合(normal)(HASH)

【SSL】1125集合(normal)(HASH)

Time Limit:2000MS
Memory Limit:65536K

Description

给定两个集合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

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

Sample Output

样例1
A equals B
样例2
B is a proper subset of A
样例3
A is a proper subset of B
样例4
A and B are disjoint
样例5
I’m confused!

思路

确定B 中的元素有几个在 A 中。

法1
用HASH
冲突处理
  线性重新散列技术易于实现且可以较好的达到目的。令数组元素个数为 S ,则当 h(k) 已经存储了元素的时候,依次探查 (h(k)+i) % S , i=1,2,3…… ,直到找到空的存储单元为止(或者从头到尾扫描一圈仍未发现空单元,这就是哈希表已经满了,发生了错误。当然这是可以通过扩大数组范围避免的)。

法2
快排,比较。
O(nlogn+mlogm+n+m);

根据交集元素个数判断A B的关系。

代码

HASH

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int hash[1000010],an,bn,m=1000000,p=1000007; 
int HASH(int x)//hash函数 
{
	return x%p;
}
int locate(int x)//x定位 
{
	int i,w=HASH(x);
	for(i=0;i<m&&hash[(w+i)%m]!=0&&hash[(w+i)%m]!=x;i++);
	return (w+i)%m;
}
void insert(int x)//插入x 
{
	int w=locate(x);
	if(hash[w]==0)
		hash[w]=x;
	return;
}
bool member(int x)//x是否在hash中 
{
	return (hash[locate(x)]==x);
}
int main()
{
	int i,x,sum=0;
	scanf("%d",&an);
	memset(hash,0,sizeof(hash));
	for(i=1;i<=an;i++)
	{
		scanf("%d",&x);
		insert(x);
	}
	scanf("%d",&bn);
	for(i=1;i<=bn;i++)
	{
		scanf("%d",&x);
		sum+=member(x);//计算交集元素个数 
	}
	if(an==bn&&sum==an)
		printf("A equals B");
	else if(sum==0)
		printf("A and B are disjoint");
	else if(an==sum&&an<bn)
		printf("A is a proper subset of B");
	else if(bn==sum&&bn<an)
		printf("B is a proper subset of A");
	else printf("I'm confused!");
	return 0;
}

SORT

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
int a[100010],b[100010];
int main()
{
	int i,j,an,bn,sum=0;
	scanf("%d",&an);
	for(i=0;i<an;i++)
		scanf("%d",&a[i]);
	scanf("%d",&bn);
	for(i=0;i<bn;i++)
		scanf("%d",&b[i]);
	sort(a,a+an);
	sort(b,b+bn);
	for(i=j=0;i<an&&j<bn;)
	{
		if(a[i]==b[j])
			sum++,i++,j++;
		else
			if(a[i]<b[j])
				i++;
			else
				j++;
	}
	if(an==bn&&sum==an)
		printf("A equals B");
	else if(sum==0)
		printf("A and B are disjoint");
	else if(an==sum&&an<bn)
		printf("A is a proper subset of B");
	else if(bn==sum&&bn<an)
		printf("B is a proper subset of A");
	else printf("I'm confused!");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值