D - Cutting Tree----并查集

xiaoxiao2021-02-28  105

D - Cutting Tree

  UVALive - 6910 

题目链接:https://cn.vjudge.net/contest/161621#problem/D

题目的意思是说给你一个森林,两个操作,1是去掉与他父亲的连边,2是查询xy是否在同一个连通块里面。

我们使用并查集,逆序来,把去边变为加边,然后判断连通性。队友敲得代码

代码:

#include <bits/stdc++.h> using namespace std; const int MAXN=20005; int n,m,k; int root; int pre[MAXN]; char s[2]; int findx(int u){ while(pre[u])u=pre[u]; return u; } int main(){ int t; scanf("%d",&t); int ca=0,u,v; while(t--){ ca++; scanf("%d%d",&n,&k); for(int i=1; i<=n; ++i){ scanf("%d",&pre[i]); } printf("Case #%d:\n",ca); while(k--){ scanf("%s",s); if(s[0]=='Q'){ scanf("%d%d",&u,&v); if(findx(u)==findx(v))puts("YES"); else puts("NO"); } else{ scanf("%d",&v); pre[v]=0; } } } return 0; }

转载请注明原文地址: https://www.6miu.com/read-30741.html

最新回复(0)