#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int N=2e5+10;
int son[N][26],idx,cnt[N];
char str[N];
void I(char str[])
{
int p=0;
for(int i=0;str[i];i++)
{
int u=str[i]-'a';
if(!son[p][u])son[p][u]=++idx;
p=son[p][u];
}
cnt[p]++;
}
int Q(char str[])
{
int p=0;
for(int i=0;str[i];i++)
{
int u=str[i]-'a';
if(!son[p][u])return 0;
p=son[p][u];
}
return cnt[p];
}
int main()
{
int t;cin>>t;
while(t--)
{
char g;
cin>>g;
getchar();
cin>>str;
if(g=='Q')
{
cout<<Q(str)<<endl;
}
else
{
I(str);
}
}
return 0;
}
//2021-07-12/09:56
- cnt数组记录到此为止该字符串出现多少次,并无需要特别注意的点
- 隐性代码
#include<iostream>
#include<algorithm>
using namespace std;
int const N=100010,M=31*N;
int n;
int a[N];
int son[M][2],idx;
void insert(int x)
{
int p=0;
for(int i=30;i>=0;i--)
{
int u=x>>i&1;
if(!son[p][u]) son[p][u]=++idx;
p=son[p][u];
}
}
int search(int x)
{
int p=0;int res=0;
for(int i=30;i>=0;i--)
{
int u=x>>i&1;
if(son[p][!u])
{
p=son[p][!u];
res=res*2+1;
}
else
{
p=son[p][u];
res=res*2;
}
}
return res;
}
int main()
{
cin>>n;
for(int i=0;i<n;i++)
{
cin>>a[i];
insert(a[i]);
}
int res=0;
for(int i=0;i<n;i++)
{
res=max(res,search(a[i]));
}
cout<<res<<endl;
}
- 要是输出一个数与一个数组中元素的最大异或对先把数组元素存成字典树然后对比
······
cnt[p]=x;
······
return cnt[p];
#include<iostream>
using namespace std;
int n,m;
const int N=1e5+10;
int p[N];
int find(int x)
{
if(p[x]!=x)p[x]=find(p[x]);
return p[x];
}
int main()
{
int n,m;cin>>n>>m;
for(int i=0;i<n;i++)
p[i]=i;
while(m--)
{
char a;cin>>a;
getchar();
int b,c;
cin>>b>>c;
if(a=='M')p[find(b)]=find(c);
else
{
if(find(b)==find(c))puts("Yes");
else puts("No");
}
}
return 0;
}
- 操作一:合并操作
p[find(a)]=find(b)
- 操作二:查找操作
if(p[x]!=x)p[x]=find(p[x]);
return p[x];
- 操作三:元素个数
- 每次添加新元素时判断,如果不在一个集合祖宗节点的size更新为新加元素作为祖宗节点的size与其的size和
union的过程更新size
if(find(a)==find(b))continue;
size[find(b)]+=size[find(a)];
p[find(a)]=find(b);
find过程更新length
#include<iostream>
using namespace std;
const int N=50010;
int d[N],p[N];
//d[x]一开始全为0,自己到自己的距离为0,d[x]代表自己到父节点的距离
int find(int x)
{
if(p[x]!=x)
{
int t=find(p[x]);
d[x]+=d[p[x]];
p[x]=t;
}
return p[x];
}
int main()
{
int n,m;
cin>>n>>m;
for(int i=1;i<=n;i++)
p[i]=i;
int res=0;
while(m--)
{
int t,x,y;
cin>>t>>x>>y;
if(x>n||y>n)res++;
else
{
int px=find(x),py=find(y);
if(t==1)
{
if(px==py&&(d[x]-d[y]+33333333333)%3)res++;
else if(px!=py)
{
p[px]=py;
d[px]=d[y]-d[x];
}
}
else
{
if(px==py&&(d[x]-d[y]-1+33333333333)%3)res++;
else if(px!=py)
{
p[px]=py;
d[px]=d[y]-d[x]+1;
}
}
}
}
cout<<res<<endl;
return 0;
}
//2021-07-12/14:37