-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgraph-valid-tree.cpp
More file actions
80 lines (67 loc) · 1.74 KB
/
graph-valid-tree.cpp
File metadata and controls
80 lines (67 loc) · 1.74 KB
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution {
public:
struct union_find {
vector<int> parent;
vector<int> size;
int components = 0;
union_find(int n = 0) {
if (n > 0)
init(n);
}
void init(int n) {
parent.resize(n + 1);
size.assign(n + 1, 1);
components = n;
for (int i = 0; i <= n; i++)
parent[i] = i;
}
int find(int x) {
return x == parent[x] ? x : parent[x] = find(parent[x]);
}
bool unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y)
return false;
if (size[x] < size[y])
swap(x, y);
parent[y] = x;
size[x] += size[y];
components--;
return true;
}
};
// ???neal_wu?union_find??
bool validTree1(int n, vector<vector<int>> &edges) {
if (n == 0) return true;
union_find un(n);
for (auto &v:edges) {
if (!un.unite(v[0], v[1])) return false;
}
return un.components==1;
}
// https://leetcode.com/problems/graph-valid-tree/discuss/69018/AC-Java-Union-Find-solution
// https://leetcode.com/problems/graph-valid-tree/discuss/69019/Simple-and-clean-c++-solution-with-detailed-explanation.
// ??????union_find??????????
// 1. ????
// 2. ????????????n?????n-1??
vector<int> parent;
bool validTree(int n, vector<vector<int>> &edges) {
if (n == 0) return true;
if (edges.size() != n-1) return false; // ?????????????
for(int i=0;i<n;i++)
parent.push_back(i);
for(auto &v:edges){
int x=find(v[0]);
int y=find(v[1]);
if(x==y) return false; // ??????
parent[x]=y;
}
return true;
}
int find(int x){
if(parent[x]==x) return x;
parent[x]=find(parent[x]);
return parent[x];
}
};