#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <map>
#include <set>
#include <stack>
usingnamespace std;
int main()
{
// ifstream in( "data.txt" );
istringstream in( "3 \n""1 2 \n""4 7 \n""8 7 \n" );
// Set up graph
map<int,vector<int>> graph;
int num_connectors;
in >> num_connectors;
for ( int i = 0; i < num_connectors; i++ )
{
int a, b;
in >> a >> b;
graph[a].push_back( b );
graph[b].push_back( a );
}
// Build up subgraphs
vector< set<int> > allSets; // Sequence of subsets
set<int> used; // Keeps track of all that are so far connected
for ( auto pr : graph )
{
int a = pr.first;
if ( used.insert( a ).second ) // If not connected before
{
set<int> subset{ a }; // New subset
// Stack up everything still available that it is connected to and not used previously
stack<int> connected;
for ( int i : graph[a] ) if ( used.insert( i ).second ) connected.push( i );
// Use the stack dynamically to expand the connected subgraph to anything not yet used
while( !connected.empty() )
{
int b = connected.top(); connected.pop();
for ( int i : graph[b] ) if ( used.insert( i ).second ) connected.push( i );
subset.insert( b );
}
// Subset is finished; add it to the sequence of subsets
allSets.push_back( subset );
}
}
// Output
cout << "Number of subgraphs = " << allSets.size() << '\n';
for ( int i = 0; i < allSets.size(); i++ )
{
cout << "Set " << i + 1 << ": ";
for ( auto e : allSets[i] ) cout << e << " ";
cout << '\n';
}
}