如果$x$和$y$相关,则连无向边$(x,y)$,边权为$0$表示相同,为$1$表示相反。
每个连通块随便选个点作为根,那么答案就是每个连通块里到根节点异或和为$0$或者$1$的点数的最大值之和。
注意到加边操作不会成环,所以用支持子树信息维护的Link-Cut Tree维护这个森林即可。
对于操作3,可以看作删边后加边,注意加边时要特判会不会成环,如果成环那么可以直接根据这个环是奇环还是偶环得到答案。
时间复杂度$O(mlog n)$。
#include<cstdio>
const int N=100010;
int n,m,ans,i,x,y,z;char op[99],op2[99];
int fa[N],w[N],f[N],son[N][2],val[N],sum[N],cnt[N][2],h[N][2];
inline bool isroot(int x){return !f[x]||son[f[x]][0]!=x&&son[f[x]][1]!=x;}
inline void up(int x){
int y;
if(y=son[x][0]){
sum[x]=sum[y];
cnt[x][0]=cnt[y][0];
cnt[x][1]=cnt[y][1];
}else sum[x]=cnt[x][0]=cnt[x][1]=0;
sum[x]^=val[x];
cnt[x][sum[x]]+=h[x][0];
cnt[x][sum[x]^1]+=h[x][1];
if(y=son[x][1]){
cnt[x][sum[x]]+=cnt[y][0];
cnt[x][sum[x]^1]+=cnt[y][1];
sum[x]^=sum[y];
}
}
inline void rotate(int x){
int y=f[x],w=son[y][1]==x;
son[y][w]=son[x][w^1];
if(son[x][w^1])f[son[x][w^1]]=y;
if(f[y]){
int z=f[y];
if(son[z][0]==y)son[z][0]=x;else if(son[z][1]==y)son[z][1]=x;
}
f[x]=f[y];f[y]=x;son[x][w^1]=y;up(y);
}
inline void splay(int x){
while(!isroot(x)){
int y=f[x];
if(!isroot(y)){if((son[f[y]][0]==y)^(son[y][0]==x))rotate(x);else rotate(y);}
rotate(x);
}
up(x);
}
inline void access(int x){
for(int y=0;x;y=x,x=f[x]){
splay(x);
int z=son[x][1];
if(z)h[x][0]+=cnt[z][0],h[x][1]+=cnt[z][1];
son[x][1]=y;
if(y)h[x][0]-=cnt[y][0],h[x][1]-=cnt[y][1];
up(x);
}
}
inline int root(int x){
access(x);
splay(x);
while(son[x][0])x=son[x][0];
splay(x);
return x;
}
inline int ask(int x){access(x);splay(x);return sum[x];}
inline int cal(int x){return cnt[x][0]>cnt[x][1]?cnt[x][0]:cnt[x][1];}
inline void cutf(int x){
ans-=cal(root(x));
access(x);
splay(x);
int y=son[x][0];
f[y]=son[x][0]=0;
up(x);
ans+=cal(root(x))+cal(root(y));
}
inline void addedge(int x,int y,int z){
splay(x);
ans-=cal(x);
if(y<=0){
val[x]=0;
up(x);
ans+=cal(x);
return;
}
ans-=cal(root(y));
val[x]=z;
access(y);
f[x]=y;
up(x);
h[y][0]+=cnt[x][0],h[y][1]+=cnt[x][1];
up(y);
ans+=cal(root(y));
}
inline void imagine(int x,int y,int z){
if(fa[x]>0)cutf(x);
if(y==-1){
addedge(x,y,z);
printf("1 %d
",ans);
addedge(x,fa[x],w[x]);
return;
}
if(root(x)==root(y)){
if(ask(x)^ask(y)^z)puts("0");else printf("1 %d
",ans);
addedge(x,fa[x],w[x]);
return;
}
addedge(x,y,z);
printf("1 %d
",ans);
cutf(x);
addedge(x,fa[x],w[x]);
}
int main(){
scanf("%d%d",&n,&m);
ans=n;
for(i=1;i<=n;i++)cnt[i][0]=h[i][0]=1;
while(m--){
scanf("%s",op);
if(op[0]=='A'){
scanf("%d%d%d",&x,&y,&z);z^=1;
fa[x]=y;
w[x]=z;
addedge(x,y,z);
}
if(op[0]=='M')printf("%d
",ans);
if(op[0]=='I'){
scanf("%d%d%d",&x,&y,&z);z^=1;
scanf("%s",op2);
scanf("%s",op2);
imagine(x,y,z);
}
}
return 0;
}