连点游戏题解

· · 个人记录

T2连点游戏

题意

给你一棵树,每个点有一个颜色,求满足起点和终点颜色相同,且路径上除起点和终点外,仅有一个点与起点颜色相同的路径数。

思路

假设这颜色相同的三个点分别为 x,y,z,则一定满足存在两个点是祖孙关系,假设为 x,y。

我们可以先 DFS 一遍,求出这个点到根路径上第一个与它颜色相同的位置,假设为 p_i。再求出 i 在 p_i 的哪一个儿子中,假设为 q_i。

那么,如果我们确定了 x,则 y 一定为 p_x。

考虑 z 在什么地方:

1.z 为 y 的祖先,则 z 一定为 p_z,有 1 的贡献。

2.\operatorname{lca}(z,y) 在 y 的父亲到 p_y 的链上(不含 p_y),则方案数为满足 p_z=p_y,z\ne y,q_y=q_z 的 z 的个数。怎么处理呢?可以将询问挂在 q_y 上,先预处理出来 p_z=p_i,q_z=q_i 的 z 的个数,到时候直接查询。

3.\operatorname{lca}(z,y)=y,q_z \ne q_x,否则不能构成一条路径。这里可以将询问转换为所有 p_z=p_y 的 z 的个数减去 p_z=p_y,q_z =q_y 的 z 的个数。同样预处理出来即可。

注意

若 p_i=0 (祖先中无与其相同颜色的),需要特殊记录一下。

#### 代码 ```cpp #include<bits/stdc++.h> using namespace std; const int N=1e6+5; namespace io {//快读 const int SIZE = (1 << 21) + 1; char ibuf[SIZE], *iS, *iT, obuf[SIZE], *oS = obuf, *oT = oS + SIZE - 1, c, qu[55]; int f, qr; // getchar #define gc() (iS == iT ? (iT = (iS = ibuf) + fread (ibuf, 1, SIZE, stdin), (iS == iT ? EOF : *iS ++)) : *iS ++) // print the remaining part inline void flush () { fwrite (obuf, 1, oS - obuf, stdout); oS = obuf; } // putchar inline void putc (char x) { *oS ++ = x; if (oS == oT) flush (); } // input a signed integer template <class I> inline void gi (I &x) { for (f = 1, c = gc(); c < '0' || c > '9'; c = gc()) if (c == '-') f = -1; for (x = 0; c <= '9' && c >= '0'; c = gc()) x = x * 10 + (c & 15); x *= f; } // print a signed integer template <class I> inline void print (I x) { if (!x) putc ('0'); if (x < 0) putc ('-'), x = -x; while (x) qu[++ qr] = x % 10 + '0', x /= 10; while (qr) putc (qu[qr --]); } } using io :: gi; using io :: putc; using io :: print; using io :: flush; int n,las[N*2],nex[N*2],h[N],tot=0,a[N],p[N],q[N],cnt3; void add(int x,int y){//链式前向星存图 las[++tot]=y; nex[tot]=h[x]; h[x]=tot; } int b[N],c[N],m[N];//b[i]记录祖先中第一个颜色为i的位置 //c[i]记录现在在b[i]的哪一个儿子中 int cnt[N],cnt2[N];//cnt记录p[z]=i的z的个数,cnt2记录q[z]=i的z的个数, void dfs(int x,int fa){ int lastb=b[a[x]]; p[x]=lastb; int lastc=c[a[x]]; q[x]=lastc; if(p[x]==0){//注意p[i]=0不能全部加到0上,所以要单独开一个数组存 m[a[x]]++; } else{ cnt[p[x]]++,cnt2[q[x]]++; } b[a[x]]=x;//更新当前颜色 for(int i=h[x];i!=0;i=nex[i]){ if(las[i]==fa){ continue; } c[a[x]]=las[i]; dfs(las[i],x); } b[a[x]]=lastb,c[a[x]]=lastc;//复原 return; } struct node{ int v,id; }f[N]; bool cmp(node fx,node fy){ return fx.v<fy.v; } int main(){ // freopen("click.in","r",stdin); // freopen("click.out","w",stdout); gi(n); for(int i=1;i<=n;i++){ gi(a[i]); f[i].id=i,f[i].v=a[i]; } sort(f+1,f+1+n,cmp); for(int i=1;i<=n;i++){//将颜色离散化 if(f[i].v!=f[i-1].v||i==1){ cnt3++; } a[f[i].id]=cnt3; } for(int i=1;i<n;i++){ int x,y; gi(x),gi(y); add(x,y),add(y,x); } dfs(1,0);//预处理 long long ans=0; for(int i=1;i<=n;i++){ if(p[i]!=0){//y不能为0 ans=ans+cnt[p[i]]-cnt2[q[i]];//情况3 if(p[p[i]]!=0){ ans=ans+(cnt2[q[p[i]]]-1+1)*2;//情况1+2 } else{//p[p[i]]=0要特殊处理 if(p[i]!=1){ ans=ans+(m[a[i]]-1)*2;//无情况1 } } } } print(ans); flush(); return 0; } ```