-
Notifications
You must be signed in to change notification settings - Fork 0
/
1082.cpp
83 lines (77 loc) · 1.58 KB
/
1082.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
/* 1082 - Connected Components */
#include<bits/stdc++.h>
using namespace std;
map<char,vector<char> >adj;
map<char,int>visited;
void dfs(char n)
{
stack<char>lis;
lis.push(n);
visited[n]=1;
set<char>ans;
set<char>::iterator it;
while(!lis.empty())
{
char up = lis.top();
ans.insert(up);
lis.pop();
for(int i=0; i<adj[up].size(); i++)
{
char v = adj[up][i];
if(visited[v]==-1)
{
visited[v]=1;
lis.push(v);
}
}
}
for(it=ans.begin(); it!=ans.end(); it++)
{
cout<<*it<<",";
}
ans.clear();
cout<<endl;
}
int main()
{
int t;
cin>>t;
for(int cas=1; cas<=t; cas++)
{
adj.clear();
visited.clear();
int node,edge;
char x,y;
cin>>node>>edge;
set<char>name;
set<char>::iterator it;
for(int i=0; i<node; i++)
{
name.insert(i+97);
}
for(int i=0; i<edge; i++)
{
cin>>x>>y;
adj[x].push_back(y);
adj[y].push_back(x);
name.insert(x);
name.insert(y);
}
printf("Case #%d:\n",cas);
for(int i=96; i<125; i++)
{
visited[i]=-1;
}
dfs('a');
int cnt=1;
for(it = name.begin(); it!=name.end(); it++)
{
if(visited[*it]==-1)
{
dfs(*it);
cnt++;
}
}
printf("%d connected components\n\n",cnt);
}
}