ZOJ-2740-Message System(并查集基础)

题目链接

ZOJ-2740

题意

给定n个点m条边,判断是不是一棵树

思路

当且仅当m=n-1且图联通时输出YES

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <bits/stdc++.h>
#include <iostream>
#define inf 0x3f3f3f3f
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int maxn = 1000+10;
const int mod = 1e9+7;
const double eps = 1e-10;
int n , m , s;
int f[maxn];
int Find(int x){ return f[x] == x ? f[x] : f[x] = Find(f[x]); }
bool same(int x , int y){ return Find(x) == Find(y) ;}
void unite(int x , int y)
{
x = Find(x) , y = Find(y);
if(x != y)f[x] = y;
}
int main(int argc, char const *argv[])
{

while(cin >> n >> m && (n+m)){
for(int i = 1 ; i <= n ; i ++)f[i] = i;
for(int i = 0 ; i < m ; i ++){
int u , v;
scanf("%d%d" , &u , &v);
unite(u , v);
}
set<int> st;
for(int i = 0 ; i < n ; i ++){
st.insert(Find(i+1));
}
if(m == n-1 && st.size() == 1){
cout << "Yes" << endl;
}
else cout << "No" << endl;
}
return 0;
}