-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathProblem C.cpp
More file actions
40 lines (34 loc) · 1.25 KB
/
Problem C.cpp
File metadata and controls
40 lines (34 loc) · 1.25 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
#include <bits/stdc++.h>
using namespace std;
map<int, int> parent; // easy storage of sets
int findRoot (int node) // find representative of node
{
if (parent[node] == node) return node; // current element is a parent
else
{
if (parent[parent[node]] != parent[node]) parent[node] = findRoot(parent[node]);
// if current parent of element is not a representative,
// find the representative and set the parent (memoizing)
return parent[node]; // return representative
}
}
int main()
{
long long crackers, N, M;
cin>>N>>M;
crackers = N; // initially everyone gets a cracker
while (M--)
{
int a, b;
cin>>a>>b;
if (!parent[a]) parent[a] = a; // every node is its own representative at first
if (!parent[b]) parent[b] = b;
int rootA = findRoot(a), rootB = findRoot(b);
if (rootA != rootB) // if nodes have different representatives, they are from different sets
{
parent[rootB] = rootA; // joining sets
crackers--; // one more member in set so one less cracker
}
}
cout<<crackers;
}