[HIHO1322]树结构判定(并查集)
题目链接:http://hihocoder.com/problemset/problem/1322
给一个图,判断这个图是不是一棵树。
判定的方法:首先是连通图,其次所有点的入度都小于等于1。
1 /* 2 ━━━━━┒ギリギリ♂ eye! 3 ┓┏┓┏┓┃キリキリ♂ mind! 4 ┛┗┛┗┛┃\○/ 5 ┓┏┓┏┓┃ / 6 ┛┗┛┗┛┃ノ) 7 ┓┏┓┏┓┃ 8 ┛┗┛┗┛┃ 9 ┓┏┓┏┓┃ 10 ┛┗┛┗┛┃ 11 ┓┏┓┏┓┃ 12 ┛┗┛┗┛┃ 13 ┓┏┓┏┓┃ 14 ┃┃┃┃┃┃ 15 ┻┻┻┻┻┻ 16 */ 17 #include <algorithm> 18 #include <iostream> 19 #include <iomanip> 20 #include <cstring> 21 #include <climits> 22 #include <complex> 23 #include <fstream> 24 #include <cassert> 25 #include <cstdio> 26 #include <bitset> 27 #include <vector> 28 #include <deque> 29 #include <queue> 30 #include <stack> 31 #include <ctime> 32 #include <set> 33 #include <map> 34 #include <cmath> 35 using namespace std; 36 #define fr first 37 #define sc second 38 #define cl clear 39 #define BUG puts("here!!!") 40 #define W(a) while(a--) 41 #define pb(a) push_back(a) 42 #define Rint(a) scanf("%d", &a) 43 #define Rll(a) scanf("%lld", &a) 44 #define Rs(a) scanf("%s", a) 45 #define Cin(a) cin >> a 46 #define FRead() freopen("in", "r", stdin) 47 #define FWrite() freopen("out", "w", stdout) 48 #define Rep(i, len) for(int i = 0; i < (len); i++) 49 #define For(i, a, len) for(int i = (a); i < (len); i++) 50 #define Cls(a) memset((a), 0, sizeof(a)) 51 #define Clr(a, x) memset((a), (x), sizeof(a)) 52 #define Full(a) memset((a), 0x7f7f, sizeof(a)) 53 #define lrt rt << 1 54 #define rrt rt << 1 | 1 55 #define pi 3.14159265359 56 #define RT return 57 #define lowbit(x) x & (-x) 58 #define onenum(x) __builtin_popcount(x) 59 typedef long long LL; 60 typedef long double LD; 61 typedef unsigned long long ULL; 62 typedef pair<int, int> pii; 63 typedef pair<string, int> psi; 64 typedef pair<LL, LL> pll; 65 typedef map<string, int> msi; 66 typedef vector<int> vi; 67 typedef vector<LL> vl; 68 typedef vector<vl> vvl; 69 typedef vector<bool> vb; 70 71 const int maxn = 505; 72 int n, m; 73 int pre[maxn]; 74 int in[maxn]; 75 76 int find(int x) { 77 return x == pre[x] ? x : pre[x] = find(pre[x]); 78 } 79 80 void unite(int x, int y) { 81 x = find(x); y = find(y); 82 if(x != y) pre[x] = y; 83 } 84 85 int main() { 86 // FRead(); 87 int T; 88 int u, v; 89 Rint(T); 90 W(T) { 91 Rint(n); Rint(m); 92 bool exflag = 0; Cls(in); 93 Rep(i, n+10) pre[i] = i; 94 Rep(i, m) { 95 Rint(u); Rint(v); 96 in[v]++; 97 unite(u, v); 98 } 99 int rt = find(pre[1]); 100 if(in[1] > 1) exflag = 1; 101 For(i, 2, n+1) { 102 if(find(pre[i]) != rt || in[i] > 1) { 103 exflag = 1; 104 break; 105 } 106 } 107 if(exflag) printf("NO\n"); 108 else printf("YES\n"); 109 } 110 RT 0; 111 }