-
Notifications
You must be signed in to change notification settings - Fork 138
/
Solution.cpp
93 lines (75 loc) · 2.11 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
84
85
86
87
88
89
90
91
92
93
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
struct Node {
int data;
};
struct BinaryNode : Node {
BinaryNode *left = NULL;
BinaryNode *right = NULL;
};
struct DisjointSetNode : Node {
DisjointSetNode *parent;
int rank = 0;
int size = 1;
};
DisjointSetNode *makeSet(int value) {
DisjointSetNode *node = new DisjointSetNode;
node->data = value;
node->parent = node;
return node;
}
DisjointSetNode *findSet(DisjointSetNode *node) {
if (node->parent == node) { return node; }
node->parent = findSet(node->parent);
return node->parent;
}
DisjointSetNode *unionSets(DisjointSetNode *firstNode, DisjointSetNode *secondNode) {
DisjointSetNode *firstNodeParent = findSet(firstNode);
DisjointSetNode *secondNodeParent = findSet(secondNode);
if (firstNodeParent == secondNodeParent) {
return firstNodeParent;
}
if (firstNodeParent->rank > secondNodeParent->rank) {
secondNodeParent->parent = firstNodeParent;
firstNodeParent->size += secondNodeParent->size;
return firstNodeParent;
}
firstNodeParent->parent = secondNodeParent;
secondNodeParent->size += firstNodeParent->size;
if (firstNodeParent->rank == secondNodeParent->rank) {
secondNodeParent->rank += 1;
}
return secondNodeParent;
}
int size(DisjointSetNode* node) {
DisjointSetNode* parent = findSet(node);
return parent->size;
}
int main() {
int N;
cin >> N;
int MIN = N + 1;
int MAX = 2;
vector<DisjointSetNode*> nodes(2*N);
for (int i = 0; i <= 2*N; i++) {
nodes[i] = makeSet(i);
}
for (int i = 0; i < N; i++) {
int edge1, edge2;
cin >> edge1 >> edge2;
unionSets(nodes[edge1], nodes[edge2]);
}
for (int i = 0; i <= 2 * N; i++) {
int nrOfNodesInSet = findSet(nodes[i])->size;
if (nrOfNodesInSet > 1) {
if (nrOfNodesInSet > MAX) { MAX = nrOfNodesInSet; }
if (nrOfNodesInSet < MIN) { MIN = nrOfNodesInSet; }
}
}
cout << MIN << " " << MAX;
return 0;
}