正题
题目链接:https://www.luogu.com.cn/problem/P4219
题目大意
nnn个点,每次有操作
- 加入一条边,保证该边连接了两个不同的连通块
- 询问经过一条边的路径数量
解题思路
考虑如何用LCTLCTLCT维护虚子树信息,只要在断边的时候把虚子树的信息维护进该节点即可。
codecodecode
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;
const int N=1e5+10;
int n,q,siz[N],size[N];
struct Link_Cut_Tree{int fa[N],t[N][2];bool r[N];stack<int> s;bool Nroot(int x){return fa[x]&&(t[fa[x]][1]==x||t[fa[x]][0]==x);}bool Direct(int x){return t[fa[x]][1]==x;}void PushUp(int x){size[x]=size[t[x][0]]+size[t[x][1]]+siz[x]+1;return;}void Rev(int x){r[x]^=1;swap(t[x][0],t[x][1]);return;}void PushDown(int x){if(!r[x])return;Rev(t[x][0]);Rev(t[x][1]);r[x]=0;return;}void Rotate(int x){int y=fa[x],z=fa[y];int xs=Direct(x),ys=Direct(y);int w=t[x][xs^1];t[x][xs^1]=y;t[y][xs]=w;if(Nroot(y))t[z][ys]=x;if(w)fa[w]=y;fa[x]=z;fa[y]=x;PushUp(y);PushUp(x);return;}void Splay(int x){s.push(x);while(Nroot(s.top()))s.push(fa[s.top()]);while(!s.empty())PushDown(s.top()),s.pop();while(Nroot(x)){int y=fa[x];if(!Nroot(y))Rotate(x);else if(Direct(x)==Direct(y))Rotate(y),Rotate(x);else Rotate(x),Rotate(x);}return;}void Access(int x){for(int y=0;x;x=fa[y=x]){Splay(x);siz[x]-=size[y]-size[t[x][1]];t[x][1]=y;PushUp(x);}return;}void MakeRoot(int x){Access(x);Splay(x);Rev(x);return;}void Link(int x,int y){MakeRoot(x);MakeRoot(y);fa[x]=y;siz[y]+=size[x];PushUp(y);return;}void Split(int x,int y){MakeRoot(x);Access(y);Splay(y);return;}
}LCT;
int main()
{scanf("%d%d",&n,&q);for(int i=1;i<=n;i++)size[i]=1;while(q--){char op[5];int x,y;scanf("%s %d%d",op,&x,&y);if(op[0]=='Q'){LCT.Split(x,y);printf("%lld\n",1ll*(siz[y]+1)*(siz[x]+1));}else LCT.Link(x,y);}return 0;
}