-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolution.cpp
83 lines (72 loc) · 1.55 KB
/
solution.cpp
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
#include <bits/stdc++.h>
using namespace std;
struct UnionFindSet {
UnionFindSet(int size) : root_(size), rank_(size, 0), size_(size, 1) {
for (int i = 0; i < size; ++i) {
root_[i] = i;
}
}
int find(int i) {
if (root_[i] == i) {
return i;
}
int root = find(root_[i]);
root_[i] = root;
return root;
}
int merge(int i, int j) {
int i_root = find(i);
int j_root = find(j);
if (i_root == j_root) {
return size_[i_root];
}
if (rank_[i_root] < rank_[j_root]) {
root_[i_root] = j_root;
size_[j_root] += size_[i_root];
size_[i_root] = 0;
return size_[j_root];
}
root_[j_root] = i_root;
size_[i_root] += size_[j_root];
size_[j_root] = 0;
if (rank_[i_root] == rank_[j_root]) {
rank_[i_root]++;
}
return size_[i_root];
}
bool resize(size_t size) {
size_t size_before = root_.size();
if (size_before >= size) {
return false;
}
root_.resize(size);
rank_.resize(size, 0);
size_.resize(size, 1);
for (int i = size_before; i < size; ++i) {
root_[i] = i;
}
return true;
}
size_t size() const { return root_.size(); }
vector<int> root_;
vector<int> rank_;
vector<int> size_;
};
int main() {
int N, M;
scanf("%d %d", &N, &M);
UnionFindSet ufs(N);
int end = 0;
for (int i = 0; i < M; ++i) {
int u, v;
scanf("%d %d", &u, &v);
if (ufs.find(u) == ufs.find(v)) {
if (end == 0) {
end = i + 1;
}
}
ufs.merge(u, v);
}
printf("%d\n", end);
return 0;
}