题目:
题意:
给出两个集合,让我们求出他们之间的关系(哈希算法模版体)
分析:
当读完题目后,倘若不加思考,定会十分头大。而当小编细心留意后,猛然发现,因为集合全都是数字,那么我们可以通过哈希算法入手,进行判重。最后在根据我们统计出来他们重复了多少个数字,从而分类输出。当然我们同样可以采用二分+快速排序来做,且在此题上,用该种做法时间效率更高。
在这里,小编会将两种代码一起奉上!
代码:(哈希版)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
using namespace std;
int a,h[149993],t=0;
int locate(int x)
{
int wz=x%149993;
while(h[wz]!=0&&h[wz]!=x)
wz++,wz%=149993;
return wz;
}
void in(int x)
{
h[locate(x)]=x;
return;
}
bool pd(int x)
{
if(h[locate(x)]==x) return 1;
return 0;
}
int main()
{
int n=0,m=0;
scanf("%d",&n);
for(int i=1;i<=n;i++)
{
scanf("%d",&a);
in(a);
}
scanf("%d",&m);
for(int i=1;i<=m;i++)
{
scanf("%d",&a);
if(pd(a)==1) t++;
}
if(t==n&&t==m) puts("A equals B");
else if(t==n&&t<m) puts("A is a proper subset of B");
else if(t==m&&t<n) puts("B is a proper subset of A");
else if(t==0) puts("A and B are disjoint");
else puts("I'm confused!");
return 0;
}
代码:(二分+快速排序)
#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#define LL long long
using namespace std;
inline LL read()
{
LL d=0,f=1;char s=getchar();
while(s<'0'||s>'9') {if(s=='-') f=-1;s=getchar();}
while(s>='0'&&s<='9') {d=d*10+s-'0';s=getchar();}
return d*f;
}
int x[100005];
int a,n,t;
void ef()
{
int l,r,mid;
l=1;r=n;
while(l<=r)
{
mid=(l+r)>>1;
if(x[mid]==a) {t++;return;}
if(x[mid]>a) r=mid-1;
else if(x[mid]<a) l=mid+1;
}
}
int main()
{
int m;
n=read();
for(int i=1;i<=n;i++) x[i]=read();
sort(x+1,x+n+1);
m=read();
for(int i=1;i<=m;i++)
{
a=read();
ef();
}
if(t==n&&t==m) puts("A equals B");
else if(t==n&&t<m) puts("A is a proper subset of B");
else if(t==m&&t<n) puts("B is a proper subset of A");
else if(t==0) puts("A and B are disjoint");
else puts("I'm confused!");
return 0;
}