集合 题解 Hash

这是一篇关于集合关系判断的题解,通过使用哈希表来解决给定两个集合A、B的关系问题。文章提供了样例输入和输出,解题思路是将集合A的元素存入哈希表,然后遍历集合B并检查其元素在哈希表中的存在状态,以此判断集合间的关系,包括真子集、相等、交集为空等。

集合 题解 Hash

题目

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


输入

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


输出

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


样例

input 1
2 55 27
2 55 27

input 2
3 9 24 1995
2 9 24

input 3
3 1 2 3
4 1 2 3 4

input 4
3 1 2 3
3 4 5 6

input 5
2 1 2
2 2 3

output 1
A equals B

output 2
B is a proper subset of A

output 3
A is a proper subset of B

output 4
A and B are disjoint

output 5
I’m confused!


解题思路

将A塞进哈希表
将B中的数去对应
最后判断是哪种关系


代码

#include<iostream>
#include<cstdio>
using namespace std;
const int p=200003;
int a[200010];
int t,x,n,m,hy; 
int h(int x)
{
	return x%p;
}  //取余
int locate(int x)
{
	int o=h(x),i=0;
	while (i<p&&a[(i+o)%p]!=x&&a[(i+o)%p]!=0)
	      i++;  //找到空位置
	return (i+o)%p;  //返回位置
}
int main()
{
	scanf("%d",&n);
	for (int i=1;i<=n;i++)
	{ 
	    scanf("%d",&x);
	    hy=locate(x);
	    a[hy]=x;  //存进哈希表
	}
	scanf("%d",&m);
	for (int i=1;i<=m;i++)
	{
		scanf("%d",&x);
		hy=locate(x);
		if (a[hy]==x)  //可以在A中找到
		   t++; //重复个数+1
	}
    if (t==n&&t==m) cout<<"A equals B";
    if (t==0) cout<<"A and B are disjoint";
    if (t==n&&t<m) cout<<"A is a proper subset of B";
    if (t==m&&t<n) cout<<"B is a proper subset of A";
    if (t<n&&t<m&&t>0) cout<<"I'm confused!";  //判断关系
    return 0;
}  
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值