题解:AT_abc404_c [ABC404C] Cycle Graph?
AnotherDream · · 题解
AT_abc404_c 题解
题意简述
给你一个图,判断这个图是不是一个环。
思路
赛时灵光一闪想到并查集,好像比搜索更好写。
首先环的点数和边数应该相等,但是不判不会影响结果。
对于前
换句话说,前
但是最后一条边不能放任不管,所有边都处理完之后,最后的图所有点度数都要为
代码
#include <bits/stdc++.h>
#define endl '\n'
#define fst ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define int long long
const int N = 2e5 + 10;
int tong[N];//度数
struct DSU {
private:
int *f;
public:
DSU(int n) {
f=new int[n+10];
for(int i=0;i<=n;i++) f[i]=i;
}
~DSU() {
delete []f;
}
inline int find(int x) {
if(f[x]==x) return x;
return f[x]=find(f[x]);
}
inline void merge(int x,int y) {
f[find(x)]=find(y);
}
inline bool ask(int x,int y) {
return find(x)==find(y);
}
} a(N);//这是并查集
int n,m;
signed main() {
fst;
cin>>n>>m;
if(n!=m) {
cout<<"No"<<endl;//显然不是环
return 0;
}
for(int i=1;i<=m;i++) {
int u,v;
cin>>u>>v;
if(a.ask(u,v)&&i<m) {//连接的两条边已经连通
cout<<"No"<<endl;
return 0;
}
a.merge(u,v);//合并两个点
tong[u]++,tong[v]++;//统计度数
}
for(int i=1;i<=n;i++) {
if(tong[i]!=2) {//环的每个点度数为2
cout<<"No"<<endl;
return 0;
}
}
cout<<"Yes"<<endl;//是环
return 0;
}