-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
90 lines (78 loc) · 2.33 KB
/
main.cpp
File metadata and controls
90 lines (78 loc) · 2.33 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
81
82
83
84
85
86
87
88
89
90
// Source: https://leetcode.com/problems/graph-valid-tree
// Title: Graph Valid Tree
// Difficulty: Medium
// Author: Mu Yang <http://muyang.pro>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer n and a list of `edges` where `edges[i] = [a_i, b_i]` indicates that there is an undirected edge between nodes `a_i` and `b_i` in the graph.
//
// Return `true` if the edges of the given graph make up a valid tree, and `false` otherwise.
//
// **Example 1:**
// https://assets.leetcode.com/uploads/2021/03/12/tree1-graph.jpg
//
// ```
// Input: n = 5, edges = [[0,1],[0,2],[0,3],[1,4]]
// Output: true
// ```
//
// **Example 2:**
// https://assets.leetcode.com/uploads/2021/03/12/tree2-graph.jpg
//
// ```
// Input: n = 5, edges = [[0,1],[1,2],[2,3],[1,3],[1,4]]
// Output: false
// ```
//
// **Constraints:**
//
// - `1 <= n <= 2000`
// - `0 <= edges.length <= 5000`
// - `edges[i].length == 2`
// - `0 <= a_i, b_i < n`
// - `a_i != b_i`
// - There are no self-loops or repeated edges.
//
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <numeric>
#include <vector>
using namespace std;
// Kruskal (Union-Find)
//
// A graph is a tree iff. it is connected and E = V-1.
class Solution {
struct UnionFind {
mutable vector<int> parents;
mutable vector<int> ranks;
int count; // connected components
UnionFind(int n) : parents(n), ranks(n, 0), count(n) { //
iota(parents.begin(), parents.end(), 0);
}
int find(int x) const {
if (parents[x] != x) {
parents[x] = find(parents[x]);
}
return parents[x];
}
void unite(int x, int y) {
x = find(x);
y = find(y);
if (x == y) return;
// Ensure rank(x) >= rank(y)
if (ranks[x] < ranks[y]) swap(x, y);
// Merge y into x
if (ranks[x] == ranks[y]) ++ranks[x];
parents[y] = x;
--count;
}
};
public:
bool validTree(int n, const vector<vector<int>>& edges) {
const int e = edges.size();
if (e != n - 1) return false;
auto uf = UnionFind(n);
for (const auto& edge : edges) {
uf.unite(edge[0], edge[1]);
}
return uf.count == 1;
}
};