File tree 1 file changed +73
-0
lines changed
1 file changed +73
-0
lines changed Original file line number Diff line number Diff line change
1
+ #include < bits/stdc++.h>
2
+ using namespace std ;
3
+ typedef long long ll;
4
+ typedef vector<ll> vi;
5
+ typedef vector<vi> vvi;
6
+ const int mod = 1000000007 ;
7
+ const int sze = 100010 ;
8
+ vi g[30 ];
9
+
10
+ int toInt (char c) { return c - ' A' ;}
11
+
12
+ void bfs (int src, vector<bool >& visited) {
13
+
14
+ queue<int > q;
15
+ q.push (src);
16
+ visited[src] = true ;
17
+
18
+ while (!q.empty ()){
19
+ int cur = q.front ();
20
+ q.pop ();
21
+
22
+ for (int i = 0 ; i < (int )g[cur].size (); ++i){
23
+ int v = g[cur][i];
24
+ if (visited[v] == false ){
25
+ q.push (v);
26
+ visited[v] = true ;
27
+ }
28
+ }
29
+ }
30
+
31
+ }
32
+
33
+ int connectedComponents (int n){
34
+ vector<bool > visited;
35
+ visited.assign (n, false );
36
+ int cc = 0 ;
37
+
38
+ for (int ver = 0 ; ver < n; ++ver) {
39
+ if (!visited[ver]) {
40
+ bfs (ver, visited);
41
+ ++cc;
42
+ }
43
+ }
44
+ return cc;
45
+ }
46
+
47
+
48
+ int main () {
49
+ int t;
50
+ cin >> t;
51
+ char inp[100 ];
52
+ cin.getline (inp, 100 ); // consumes all the whitespace after t
53
+ cin.getline (inp , 100 ); // consumes the first line
54
+
55
+ while (t--) {
56
+ char n; cin >> n;
57
+ int N = toInt (n) + 1 ;
58
+
59
+ cin.getline (inp, 100 );
60
+ // reading edges
61
+
62
+ while (cin.getline (inp, 100 ) && strlen (inp) > 0 ) {
63
+ g[toInt (inp[0 ])].push_back (toInt (inp[1 ]));
64
+ g[toInt (inp[1 ])].push_back (toInt (inp[0 ]));
65
+ }
66
+
67
+ cout << connectedComponents (N) << " \n " ;
68
+ // output of the two consecutive shall be seperated by a blank line
69
+ if (t)
70
+ cout << " \n " ;
71
+ for (auto & v : g) v.clear (); // clearing all adjlists in the g array
72
+ }
73
+ }
You can’t perform that action at this time.
0 commit comments