-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUVa-793.cpp
More file actions
80 lines (66 loc) · 1.71 KB
/
UVa-793.cpp
File metadata and controls
80 lines (66 loc) · 1.71 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
#include <bits/stdc++.h>
using namespace std;
#define vi vector<int>
#include <iostream>
// this problem is easy but it gets a runtime error, even the online solutions get RTE.
// it's based on the idea of the UFDS (union find disjoin set)
class UnionFind
{ // OOP style
private:
vi p, rank;
public:
UnionFind(int N)
{
rank.assign(N, 0);
p.assign(N, 0);
for (int i = 0; i < N; i++)
p[i] = i;
}
int findSet(int i) { return (p[i] == i) ? i : (p[i] = findSet(p[i])); }
bool isSameSet(int i, int j) { return findSet(i) == findSet(j); }
void unionSet(int i, int j)
{
if (!isSameSet(i, j))
{
// if from different set
int x = findSet(i), y = findSet(j);
if (rank[x] > rank[y])
p[y] = x;
// rank keeps the tree short
else
{
p[x] = y;
if (rank[x] == rank[y])
rank[y]++;
}
}
}
};
int main() {
string s;
int tc;
scanf("%d", &tc);
for (int t = 1; t <= tc; t++) {
int n;
scanf("\n%d\n", &n);
int i, j;
//cout << n; // worked
UnionFind union_find(n);
int con, dis;
con = dis = 0;
char op;
while (getline(cin, s) && not s.empty()) {
istringstream iss(s);
iss >> op >> i >> j;
if (op == 'q') {
union_find.isSameSet(i, j) ? con++ : dis++;
}
else {
union_find.unionSet(i, j);
}
}
if (t != 1)
printf("\n");
printf("%d,%d\n",con, dis);
}
}