链接:https://ac.nowcoder.com/acm/contest/553/I
思路:离线整棵树,用并查集维护下联通的情况,因为值只有60个,用2的x(1<=x<=60)次方表示,树链剖分线段树区间取或维护,取得的值只要数二进制里面有多少个1就代表有多少个相同的数。
实现代码;
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define mid ll m = (l + r) >> 1
const int M = 3e5+;
ll sum[M<<],f[M],head[M],son[M],siz[M],fa[M],dep[M];
ll cnt,cnt1,n,tid[M],top[M],a[M],op[M],u[M],v[M],ans[M];
struct node{
ll to,next;
}e[M];
ll Find(ll x){
if(x == f[x]) return x;
return f[x] = Find(f[x]);
} void add(ll u,ll v){
e[++cnt1].to=v;e[cnt1].next=head[u];head[u]=cnt1;
e[++cnt1].to=u;e[cnt1].next=head[v];head[v]=cnt1;
}
void dfs1(ll u,ll faz,ll deep){
dep[u] = deep;
siz[u] = ;
fa[u] = faz;
//cout<<u<<" "<<faz<<" "<<deep<<endl;
for(ll i = head[u];i ;i=e[i].next){
ll v = e[i].to;
if(v != fa[u]){
dfs1(v,u,deep+);
siz[u] += siz[v];
if(son[u]==-||siz[v]>siz[son[u]])
son[u] = v;
}
}
} void dfs2(ll u,ll t){
top[u] = t;
tid[u] = cnt;
//cout<<1<<endl;
cnt++;
if(son[u] == -) return ;
dfs2(son[u],t);
for(ll i = head[u];i;i=e[i].next){
ll v = e[i].to;
if(v != son[u]&&v != fa[u])
dfs2(v,v);
}
} void update(ll p,ll c,ll l,ll r,ll rt){
if(l == r){
sum[rt] = c;
return ;
}
mid;
if(p <= m) update(p,c,lson);
else update(p,c,rson);
sum[rt] = sum[rt<<] | sum[rt<<|];
} ll query(ll L,ll R,ll l,ll r,ll rt){
if(L <= l&&R >= r){
return sum[rt];
}
mid;
ll ret = ;
if(L <= m) ret |= query(L,R,lson);
if(R > m) ret |= query(L,R,rson);
return ret;
} ll solve(ll x){
ll ans = ;
while(x){
ans++;
x -= (x&-x);
}
return ans;
} ll ask(ll x,ll y){
ll ans = ;
ll fx = top[x],fy = top[y];
while(fx != fy){
if(dep[fx] < dep[fy]) swap(x,y),swap(fx,fy);
ans |= query(tid[fx],tid[x],,n,);
x = fa[fx]; fx = top[x];
}
if(dep[x] > dep[y]) swap(x,y);
ans |= query(tid[x],tid[y],,n,);
return ans;
} int main()
{
ios::sync_with_stdio();
cin.tie(); cout.tie();
ll q; cnt = ;
cin>>n>>q;
memset(son,-,sizeof(son));
for(ll i = ;i <= n;i ++){
cin>>a[i];f[i] = i;
}
for(ll i = ;i <= q;i ++){
cin>>op[i]>>u[i]>>v[i];
if(op[i] == ){
ll fx = Find(u[i]),fy = Find(v[i]);
if(fx != fy) f[fx] = fy,add(u[i],v[i]),ans[i]=;
}
else{
ll fx = Find(u[i]),fy = Find(v[i]);
if(fx != fy) ans[i] = -;
}
}
dfs1(,,); dfs2(,);
for(ll i = ;i <= q;i ++){
if(op[i] == &&ans[i]==){
ll num = (a[u[i]] + a[v[i]])/;
a[u[i]] = a[v[i]] = num;
update(tid[u[i]],1LL<<num,,n,);
update(tid[v[i]],1LL<<num,,n,); }
else if(op[i] == &&ans[i]!=-){
ans[i] = solve(ask(u[i],v[i]));
}
}
for(ll i = ;i <= q;i ++)
if(op[i] == ) cout<<ans[i]<<endl; }