ssl1125-集合【哈希表&二分查找+快排】

前言

今天学哈希表,然后就第一节晚修赶快写完作业就上了做题了,然后就做完了这道题get√。


正题


题目

给出两个集合:
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!”
然后集合大小小于10^5,集合中的数大小小于10^9


输入输出(建议无视)

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!


解题思路

二分查找+快排

这就是用快排排好第一个集合然后用二分查找找另一个集合里的数。

(正题)哈希表

用哈希表储存第一个集合,然后快速判断集合中有没有另一个集合中的数


代码

二分查找+快排

#include<cstdio>
#include<algorithm>//c++算法库自带快排
using namespace std;
int n1,n2,a1[100001],a2[100001],l,r,ans,s,mid;
char c;
int main()
{
    scanf("%d",&n1);
    for (int i=1;i<=n1;i++)
    {
        scanf("%d",&a1[i]);
    }
    scanf("%d",&n2);
    for (int i=1;i<=n2;i++)
    {
        scanf("%d",&a2[i]);
    }
    sort(a1+1,a1+1+n1);//快排
    for (int i=1;i<=n2;i++)
    {
        ans=a2[i];//查找对象
        l=1;r=n1;//范围
        while (l<=r)
        {
            mid=(l+r)/2;//取中间值
            if (a1[mid]==ans) break;//找到就退出
            if (a1[mid]<ans) l=mid+1;
            else r=mid-1;//缩小范围
        }
        if (a1[mid]==ans) s++;//统计相同数
    }
    //以下输出不解释
    if (s==n1 && s==n2) printf("A equals B");
    else if (s==n1) printf("A is a proper subset of B");
    else if (s==n2) printf("B is a proper subset of A");
    else if (s==0) printf("A and B are disjoint");
    else printf("I'm confused!");
}

哈希表

#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=149993;//开个大一些的素数减少冲突
int n1,n2,hash[maxn],x,s;
int hashmath(int x)
{
    return x%maxn;
}//哈希函数
int locate(int x)//寻找位置
{
    int i=0,w=hashmath(x);
    while (i<maxn && hash[(w+i)%maxn]!=0 && hash[(w+i)%maxn]!=x)
    //找到空位,相同的或没有空位(数组开大已经避免了)
      i++;//下一个
    return (w+i)%maxn;//返回值
}
void ins(int x)//插入函数
{
    int w=locate(x);//寻找位置
    hash[w]=x;//插入
}
bool find(int x)//查找
{
    int w=locate(x);//寻找位置
    if (hash[w]==x) return true;//是否存在
    else return false;
}
int main()
{
    scanf("%d",&n1);
    for (int i=1;i<=n1;i++)
    {
        scanf("%d",&x);
        ins(x);//插入
    }
    scanf("%d",&n2);
    for (int i=1;i<=n2;i++)
    {
        scanf("%d",&x);
        if (find(x)) s++;//统计次数
    }
    //以下输出
    if (s==n1 && s==n2) printf("A equals B");
    else if (s==n1) printf("A is a proper subset of B");
    else if (s==n2) printf("B is a proper subset of A");
    else if (s==0) printf("A and B are disjoint");
    else printf("I'm confused!");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值