[BZOJ4998]星球联盟
IX.[BZOJ4998]星球联盟
这题就比较套路了(虽然我的程序还好好让我debug了一会),比上一题还要简单,直接暴力维护点双即可。
代码:
#include<bits/stdc++.h>
using namespace std;
#define lson t[x].ch[0]
#define rson t[x].ch[1]
int n,m,p,dsu[200100],sz[200100];
int find(int x){
return dsu[x]==x?x:dsu[x]=find(dsu[x]);
}
void merge(int x,int y){
x=find(x),y=find(y);
if(x==y)return;
if(sz[x]<sz[y])dsu[x]=y,sz[y]+=sz[x];
else dsu[y]=x,sz[x]+=sz[y];
}
struct LCT{
int ch[2],fa,val,sum;
bool rev;
}t[200100];
int identify(int x){
if(t[find(t[x].fa)].ch[0]==x)return 0;
if(t[find(t[x].fa)].ch[1]==x)return 1;
return -1;
}
void REV(int x){
t[x].rev^=1,swap(lson,rson);
}
void pushup(int x){
t[x].sum=t[x].val;
if(lson)t[x].sum+=t[lson].sum;
if(rson)t[x].sum+=t[rson].sum;
}
void pushdown(int x){
if(!t[x].rev)return;
if(lson)REV(lson);
if(rson)REV(rson);
t[x].rev=0;
}
void rotate(int x){
int y=find(t[x].fa);
int z=find(t[y].fa);
int dirx=identify(x);
int diry=identify(y);
int b=t[x].ch[!dirx];
if(diry!=-1)t[z].ch[diry]=x;t[x].fa=z;
if(b)t[b].fa=y;t[y].ch[dirx]=b;
t[x].ch[!dirx]=y,t[y].fa=x;
pushup(y),pushup(x);
}
void pushall(int x){
if(identify(x)!=-1)pushall(t[x].fa=find(t[x].fa));
pushdown(x);
}
void splay(int x){
pushall(x);
while(identify(x)!=-1){
int fa=t[x].fa;
if(identify(fa)==-1)rotate(x);
else if(identify(fa)==identify(x))rotate(fa),rotate(x);
else rotate(x),rotate(x);
}
}
void access(int x){
for(int y=0;x;x=find(t[y=x].fa))splay(x),rson=y,pushup(x);
}
void makeroot(int x){
access(x),splay(x),REV(x);
}
void split(int x,int y){
makeroot(x),access(y),splay(y);
}
int findroot(int x){
access(x),splay(x);
pushdown(x);
while(lson)x=lson,pushdown(x);
splay(x);
return x;
}
void shrink(int x,int y){
merge(x,y);
if(x!=y)t[y].val+=t[x].val,t[x].fa=0;
pushdown(x);
if(lson)shrink(lson,y);
if(rson)shrink(rson,y);
lson=rson=0;
}
int link(int x,int y){
if(findroot(x)==findroot(y)){split(x,y),shrink(y,y);return sz[find(y)];}
else{makeroot(x),t[x].fa=y;return -1;}
}
int main(){
scanf("%d%d%d",&n,&m,&p);
for(int i=1;i<=n;i++)sz[i]=t[i].val=t[i].sum=1,dsu[i]=i;
for(int i=1,x,y;i<=m;i++)scanf("%d%d",&x,&y),x=find(x),y=find(y),link(x,y);
for(int i=1,x,y,z;i<=p;i++){
scanf("%d%d",&x,&y),x=find(x),y=find(y),z=link(x,y);
if(z==-1)puts("No");else printf("%d\n",z);
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 【杂谈】分布式事务——高大上的无用知识?