UVALive 6910 Cutting Tree(离线逆序并查集)

时间:2022-09-20 19:44:58

【题目】:(地址:)

http://acm.hust.edu.cn/vjudge/contest/view.action?cid=97671#problem/E

【题意】:

给出多棵树和两类操作:操作(C  x)删除结点 x 与其父结点的连边;操作(Q a b)询问 a b 是否连通。

【解题思路】:

连通性的查询容易想到用并查集,关键在于如何处理删边。

考虑到删边的难点在于查询时的路径压缩导致某些结点与其父结点"不直接相连",这里使用离线处理,在查询之前把所有该删的边删除,同时逆序处理询问操作;当逆序处理到删边操作时,复原删掉的边(删除变为增边)。

【代码】:(上了个比较标准的并查集模板)

 #include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<stack>
#include<algorithm>
#define LL long long
#define maxn 25000
#define IN freopen("in.txt","r",stdin);
using namespace std; struct Union_Find_Set{ int fa[maxn]; /*每个结点的父亲节点编号*/
int rank[maxn]; /*树的高度*/ /*构造并查集并初始化*/
void make_set()
{
for(int i=; i<maxn; i++){
fa[i] = i; /*初始时本身构成一个集合,根为本身*/
rank[i] = ;
}
} /*递归查找结点所在树的根节点*/
int find_set(int x)
{
/*路径压缩*/
return x!=fa[x]? fa[x]=find_set(fa[x]) : x;
} /*合并两个集合*/
void unite_set(int x, int y)
{
x = find_set(x);
y = find_set(y);
/*记录树的高度防止合并后退化,rank小的向rank大的连接*/
if(rank[x] < rank[y]) swap(x,y);
fa[y] = x; /*合并*/
if(rank[x] == rank[y]) rank[x]++; /*高度相同则加1*/
} /*判断两结点是否属于同一集合*/
bool same_set(int x, int y)
{
return find_set(x) == find_set(y);
}
}UFS; int n,q;
struct node{
char type;
int first, second;
}; stack<node> s;
stack<bool> ans; int main(int argc, char const *argv[])
{
//IN; int t,ca=;scanf("%d",&t);
while(t--)
{
scanf("%d %d",&n,&q); while(!s.empty()) s.pop();
while(!ans.empty()) ans.pop();
UFS.make_set(); for(int i=; i<=n; i++){
scanf("%d",&UFS.fa[i]);
if(!UFS.fa[i]) UFS.fa[i] = i;
} for(int i=; i<=q; i++)
{
node tmp_node;
getchar();
scanf("%c",&tmp_node.type);
if(tmp_node.type=='Q'){
scanf("%d %d",&tmp_node.first, &tmp_node.second);
}
else{
scanf("%d",&tmp_node.first);
tmp_node.second = UFS.fa[tmp_node.first];
/*离线处理--询问之前删边,避免路径压缩导致删边失效*/
UFS.fa[tmp_node.first] = tmp_node.first;
}
s.push(tmp_node);
} while(q--)
{
node tmp_node = s.top(); s.pop(); if(tmp_node.type=='Q'){
if(UFS.same_set(tmp_node.first, tmp_node.second)) ans.push();
else ans.push();
}
else{
UFS.fa[tmp_node.first] = tmp_node.second;
}
} printf("Case #%d:\n", ca++);
while(!ans.empty())
{
if(ans.top() == ) puts("YES");
else puts("NO");
ans.pop();
}
} return ;
}