-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathP459.cpp
95 lines (84 loc) · 2 KB
/
P459.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
94
95
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <stack>
typedef std::pair<int,int> PP;
unsigned int readUInt() {
unsigned int ret = 0;
char w[20];
gets(w);
for(int i = 0; i < 20; ++i) {
if(!(w[i] >= '0' && w[i] <= '9'))
break;
ret = ret * 10 + (w[i]-'0');
}
return ret;
}
bool readEdge(PP &edge) {
char w[10];
if(!gets(w) || w[0] < 'A' || w[0] > 'Z')
return false;
edge.first = w[0]-'A';
edge.second = w[1]-'A';
return true;
}
int main() {
char line[10];
int citizens[26]; // citizen -> edge index.
PP edges[1000];
unsigned int cases = readUInt();
gets(line); // Empty line
for(unsigned int cas = 0; cas < cases; ++cas) {
if(cas != 0)
std::cout << std::endl;
// Read number of citizens:
gets(line);
int N = line[0]-'A'+1; //number of citizens.
for(int i = 0; i < N; ++i)
citizens[i] = -2;
//std::cerr << "Citizens: " << N << std::endl;
// Read edges:
PP edge;
int M = 0;
for(; readEdge(edge); ++M) {
if(edge.first == edge.second)
continue;
edges[2*M] = edge;
std::swap(edge.first, edge.second);
edges[2*M+1] = edge;
}
std::sort(edges, edges+2*M);
int prev = -1;
for(int i = 0; i < 2*M; ++i) {
if(edges[i].first != prev) {
prev = edges[i].first;
citizens[prev] = i;
}
}
//std::cerr << "Edges: " << M << std::endl;
// Compute connected components:
int components = 0;
std::stack<int> s;
for(int i = 0; i < N; ++i) {
if(citizens[i] == -1)
continue; // Already handled.
++components;
if(citizens[i] == -2) {
continue; // No edges.
}
s.push(i);
while(!s.empty()) {
int citizen = s.top();
s.pop();
if(citizens[citizen] == -1)
continue; // Already handled.
for(int j = citizens[citizen]; edges[j].first == citizen; ++j) {
s.push(edges[j].second);
}
citizens[citizen] = -1;
} // while(!s.empty)
} // for i
std::cout << components << std::endl;
} // for case
return 0;
}