【BZOJ4530】大融合(Link-Cut Tree)
阿新 • • 發佈:2018-01-22
數據 ota mes read names 編號 ble pla str
【BZOJ4530】大融合(Link-Cut Tree)
題面
討厭權限題!!!
Loj鏈接
題目描述
小強要在 N個孤立的星球上建立起一套通信系統。這套通信系統就是連接 N個點的一個樹。這個樹的邊是一條一條添加上去的。在某個時刻,一條邊的負載就是它所在的當前能夠聯通的樹上路過它的簡單路徑的數量。
例如,在上圖中,現在一共有五條邊。其中,(3,8)這條邊的負載是 6,因為有六條簡單路徑 2?3?8, 2?3?8?7, 3?8, 3?8?7, 4?3?8, 4?3?8?72-3-8,?2-3-8-7,?3-8,?3-8-7,?4-3-8,?4-3-8-72?3?8, 2?3?8?7, 3?8, 3?8?7, 4?3?8, 4?3?8?7 路過了 (3,8)。
現在,你的任務就是隨著邊的添加,動態的回答小強對於某些邊的負載的詢問。
輸入格式
第一行包含兩個整數 N,QN,QN,Q,表示星球的數量和操作的數量。星球從 111 開始編號。
接下來的 QQQ 行,每行是如下兩種格式之一:
A x y 表示在 xxx 和 yyy 之間連一條邊。保證之前 xxx 和 yyy 是不聯通的。
Q x y 表示詢問 (x,y)(x,y)(x,y) 這條邊上的負載。保證 xxx 和 yyy 之間有一條邊。
輸出格式
對每個查詢操作,輸出被查詢的邊的負載。
樣例
樣例輸入
8 6
A 2 3
A 3 4
A 3 8
A 8 7
A 6 5
Q 3 8
樣例輸出
6
數據範圍與提示
對於所有數據,\(1≤N,Q≤100000\)
題解
\(Link-Cut\ Tree\)維護子樹信息
不僅僅維護實兒子
還需要維護虛兒子
就相當於在原樹中的兒子數量啦
我也不知道為什麽
。。。
以後知道了就補一下
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<set>
#include<map>
#include<vector>
#include<queue>
using namespace std;
#define MAX 120000
#define lson (t[x].ch[0])
#define rson (t[x].ch[1])
inline int read()
{
int x=0,t=1;char ch=getchar();
while((ch<'0'||ch>'9')&&ch!='-')ch=getchar();
if(ch=='-')t=-1,ch=getchar();
while(ch<='9'&&ch>='0')x=x*10+ch-48,ch=getchar();
return x*t;
}
struct Node
{
int ch[2],ff;
int rev,size,sum;
}t[MAX];
int S[MAX],top;
int n,Q;
bool isroot(int x){return t[t[x].ff].ch[0]!=x&&t[t[x].ff].ch[1]!=x;}
void pushup(int x){t[x].sum=t[lson].sum+t[rson].sum+t[x].size+1;}
void rotate(int x)
{
int y=t[x].ff,z=t[y].ff;
int k=t[y].ch[1]==x;
if(!isroot(y))t[z].ch[t[z].ch[1]==y]=x;t[x].ff=z;
t[y].ch[k]=t[x].ch[k^1];t[t[x].ch[k^1]].ff=y;
t[x].ch[k^1]=y;t[y].ff=x;
pushup(y);pushup(x);
}
void pushdown(int x)
{
if(!t[x].rev)return;
swap(lson,rson);
if(lson)t[lson].rev^=1;
if(rson)t[rson].rev^=1;
t[x].rev^=1;
}
void Splay(int x)
{
S[top=1]=x;
for(int i=x;!isroot(i);i=t[i].ff)S[++top]=t[i].ff;
while(top)pushdown(S[top--]);
while(!isroot(x))
{
int y=t[x].ff,z=t[y].ff;
if(!isroot(y))
(t[y].ch[1]==x)^(t[z].ch[1]==y)?rotate(x):rotate(y);
rotate(x);
}
}
void access(int x){for(int y=0;x;y=x,x=t[x].ff)Splay(x),t[x].size+=t[rson].sum-t[y].sum,t[x].ch[1]=y,pushup(x);}
void makeroot(int x){access(x);Splay(x);t[x].rev^=1;}
void split(int x,int y){makeroot(x);access(y);Splay(y);}
void cut(int x,int y){split(x,y);t[y].ch[0]=t[x].ff=0;pushup(y);}
void link(int x,int y){makeroot(x);makeroot(y);t[x].ff=y;t[y].size+=t[x].sum;pushup(y);}
int findroot(int x){makeroot(x);while(lson)x=lson;return x;}
int main()
{
n=read();Q=read();
char ch[2];int u,v;
while(Q--)
{
scanf("%s",ch);u=read(),v=read();
if(ch[0]=='A')link(u,v);
else split(u,v),printf("%lld\n",1ll*t[u].sum*(t[v].sum-t[u].sum));
}
return 0;
}
【BZOJ4530】大融合(Link-Cut Tree)