【SDOI2011】染色

来源:互联网 发布:js数组排序 编辑:程序博客网 时间:2024/04/27 03:14

Description

给出一棵树,每个点有颜色。
m次操作,每次操作把一条路径上的颜色都修改成c,
或询问一条路径上的颜色段数。
n,m<=10^5

Solution

简单的链剖题。
每个区间维护颜色段数和左右端点的颜色就好了。
然而这道题会爆栈!!!而且要写有方向的往上跳~~
于是我方了~~
然后就滚回去写LCT了。
为了练手我就写了个静态LCT(然并卵)
然后发现x=y时跪了。。。
有点奥妙重重啊233

Code

#include<cstdio>#include<cstring>#include<algorithm>#define fo(i,a,b) for(int i=a;i<=b;i++)#define rep(i,a) for(int i=last[a];i;i=next[i])#define N 100005using namespace std;int t[N][2],f[N],key[N],le[N],ri[N],sz[N],lazy[N],d[N],p[N],lca;int to[N*2],next[N*2],last[N],fa[N];int n,m,x,y,z,l,ans,deep[N],q[N];char s[1];void add(int x,int y) {    to[++l]=y;next[l]=last[x];last[x]=l;}int son(int x) {    return t[f[x]][1]==x;}void updata(int x) {    if (t[x][0]) le[x]=le[t[x][0]];    else le[x]=key[x];    if (t[x][1]) ri[x]=ri[t[x][1]];    else ri[x]=key[x];    sz[x]=sz[t[x][0]]+sz[t[x][1]]+1;    if (t[x][0]&&ri[t[x][0]]==key[x]) sz[x]--;    if (t[x][1]&&le[t[x][1]]==key[x]) sz[x]--;}void back(int x,int y) {    if (!x) return;    sz[x]=1;le[x]=ri[x]=lazy[x]=key[x]=y;}void down(int x) {    if (lazy[x]) {        back(t[x][0],lazy[x]);        back(t[x][1],lazy[x]);        lazy[x]=0;    }}void remove(int x,int y) {    do {        d[++d[0]]=x;x=f[x];    } while (x!=y);    while (d[0]) down(d[d[0]--]);} void rotate(int x) {    int y=f[x],z=son(x);f[x]=f[y];    if (f[x]) t[f[x]][son(y)]=x;    else p[x]=p[y],p[y]=0;    if (t[x][1-z]) f[t[x][1-z]]=y;    f[y]=x;t[y][z]=t[x][1-z];t[x][1-z]=y;    updata(y);updata(x);}void splay(int x,int y) {    remove(x,y);    while (f[x]!=y) {        if (f[f[x]]!=y)             if (son(x)==son(f[x])) rotate(f[x]);            else rotate(x);        rotate(x);    }}void access(int x) {    int y=0;    while (x) {        splay(x,0);        f[t[x][1]]=0;p[t[x][1]]=x;        t[x][1]=y;f[y]=x;p[y]=0;        updata(x);y=x;x=p[x];    }lca=y;}int main() {    scanf("%d%d",&n,&m);    fo(i,1,n) scanf("%d",&key[i]);    fo(i,1,n-1) scanf("%d%d",&x,&y),add(x,y),add(y,x);    int i=0,j=1;deep[1]=q[1]=1;    while (i<j) {        rep(k,q[++i]) if (to[k]!=fa[q[i]]) {            fa[to[k]]=q[i];deep[to[k]]=deep[q[i]]+1;            p[to[k]]=q[i];q[++j]=to[k];        }    }    for(;m;m--) {        scanf("%s%d%d",s,&x,&y);        if(s[0]=='C'){            scanf("%d",&z);            if (x==y) {splay(x,0);key[x]=z;continue;}            if(deep[x]<deep[y])swap(x,y);            access(x);access(y);splay(x,0);            key[lca]=z;back(x,z);            back(t[lca][1],z);updata(lca);        }        else{            if (x==y) {printf("1\n");continue;}            if(deep[x]<deep[y])swap(x,y);            access(x);access(y);splay(x,0);            ans=sz[x]+sz[t[lca][1]]+1;            if(le[x]==key[lca])ans--;            if(key[lca]==le[t[lca][1]])ans--;            printf("%d\n",ans);        }    }}
0 0