题目概述
有 n n 个点, 个操作。操作有两种:1.连接 x x 和 。2.询问经过 (x,y) ( x , y ) 的路径数。
解题报告
答案显然就是 si(x)×si(y) s i ( x ) × s i ( y ) ,但是有连接操作,可以考虑LCT(好像有很多离线做法,我不是很清楚QAQ)。问题就是如何维护子树信息。
LCT实链上的信息可以方便维护,所以我们关注虚边:虚边只在Access和Link的时候改变。那么我们只需要记录两个信息 si[x][0],si[x][1] s i [ x ] [ 0 ] , s i [ x ] [ 1 ] 表示虚边节点数以及”总节点数”1,则 si[x][1]=si[L[x]][1]+si[R[x]][1]+si[x][0]+1 s i [ x ] [ 1 ] = s i [ L [ x ] ] [ 1 ] + s i [ R [ x ] ] [ 1 ] + s i [ x ] [ 0 ] + 1 。然后Access和Link的时候顺便维护一下 si[x][0] s i [ x ] [ 0 ] 就行了。注意Link(x,y)的时候一定要让 y y 成为根,否则无法更新信息(如果 不是根,将引起大量信息改动)。
示例程序
#include<cstdio>
#include<cctype>
#include<algorithm>
using namespace std;
typedef long long LL;
const int maxn=100000;
int n,te,son[maxn+5][2],fa[maxn+5],si[maxn+5][2];bool flip[maxn+5];
#define Eoln(x) ((x)==10||(x)==13||(x)==EOF)
inline char readc(){
static char buf[100000],*l=buf,*r=buf;
if (l==r) r=(l=buf)+fread(buf,1,100000,stdin);
if (l==r) return EOF;return *l++;
}
inline int readi(int &x){
int tot=0,f=1;char ch=readc(),lst='+';
while (!isdigit(ch)) {if (ch==EOF) return EOF;lst=ch;ch=readc();}
if (lst=='-') f=-f;
while (isdigit(ch)) tot=(tot<<3)+(tot<<1)+ch-48,ch=readc();
return x=tot*f,Eoln(ch);
}
inline char getupr() {char ch=readc();while (!isupper(ch)) ch=readc();return ch;}
#define is_ro(p) ((p)!=son[fa[p]][0]&&(p)!=son[fa[p]][1])
#define Son(p) ((p)==son[fa[p]][1])
inline void Pushup(int p) {si[p][1]=si[son[p][0]][1]+si[son[p][1]][1]+si[p][0]+1;}
inline void Rotate(int t){
int p=fa[t],d=Son(t);son[p][d]=son[t][d^1];son[t][d^1]=p;
Pushup(p);Pushup(t);if (!is_ro(p)) son[fa[p]][Son(p)]=t;
if (son[p][d]) fa[son[p][d]]=p;fa[t]=fa[p];fa[p]=t;
}
inline void Addflip(int p) {swap(son[p][0],son[p][1]);flip[p]^=1;}
inline void Pushdown(int p) {if (flip[p]) flip[p]^=1,Addflip(son[p][0]),Addflip(son[p][1]);}
inline void Splay(int p){
static int top,stk[maxn+5];stk[top=1]=p;
for (int i=p;!is_ro(i);i=fa[i]) stk[++top]=fa[i];
while (top) Pushdown(stk[top--]);
for (int pre=fa[p];!is_ro(p);Rotate(p),pre=fa[p])
if (!is_ro(pre)) Rotate(Son(p)==Son(pre)?pre:p);
}
inline void Access(int p){
for (int lst=0;p;Pushup(p),lst=p,p=fa[p])
Splay(p),si[p][0]+=si[son[p][1]][1]-si[lst][1],son[p][1]=lst;
}
inline void Makero(int x) {Access(x);Splay(x);Addflip(x);}
inline void Link(int x,int y) {Makero(x);Makero(y);fa[x]=y;si[y][0]+=si[x][1];Pushup(y);}
inline LL Ask(int x,int y) {Makero(x);Access(y);Splay(y);return (LL)(si[y][1]-si[x][1])*si[x][1];}
int main(){
freopen("program.in","r",stdin);
freopen("program.out","w",stdout);
readi(n);for (int i=1;i<=n;i++) si[i][1]=1;
for (readi(te);te;te--){
char td=getupr();int x,y;readi(x);readi(y);
if (td=='A') Link(x,y); else printf("%lld\n",Ask(x,y));
}
return 0;
}
- 2018.7.2UPD:最近频繁炸出以前的锅啊2333…… si[x][1] s i [ x ] [ 1 ] 原来写成了总节点数,实际上应该是虚边节点数加上Splay中子树的节点数。所以使用的时候要小心点。 ↩