My program works fine for normal range inputs but fails for test case inputs which has N and C in the order of 100000 by giving time limit exception.
Is there any better way to crack this question?
This problem looks to be finding strongly-connected components in a graph.
I do not understand what your “identity number” is or how it affects your output.
Also, I do not understand how
10 9 4
#include <iostream>
#include <fstream>
#include <vector>
#include <set>
usingnamespace std;
void writeGroups( const vector< set<int> > &groups );
int main()
{
int N, C;
int i, j;
vector< set<int> > groups;
ifstream in( "in.txt" );
in >> N >> C;
vector<int> setnum( 1 + N, -1 ); // sentinel -1 means none yet assigned
while ( C-- ) // read C lines
{
in >> i >> j;
int si = setnum[i], sj = setnum[j];
if ( si < 0 && sj < 0 ) // neither yet assigned - create a new set
{
set<int> S = { i, j };
groups.push_back( S );
setnum[i] = setnum[j] = groups.size() - 1;
}
elseif ( si < 0 ) // assign i to j's set
{
groups[sj].insert( i );
setnum[i] = sj;
}
elseif ( sj < 0 ) // assign j to i's set
{
groups[si].insert( j );
setnum[j] = si;
}
elseif ( si != sj ) // move the smaller set into the larger one
{
if ( groups[sj].size() < groups[si].size() )
{
for ( int k : groups[sj] ) setnum[k] = si;
groups[si].insert( groups[sj].begin(), groups[sj].end() );
groups[sj].clear();
}
else
{
for ( int k : groups[si] ) setnum[k] = sj;
groups[sj].insert( groups[si].begin(), groups[si].end() );
groups[si].clear();
}
}
}
int largest = 0;
for ( auto S : groups ) if ( S.size() > largest ) largest = S.size();
cout << largest << '\n';
// Checks // COMMENT THE FOLLOWING TWO LINES OUT IF YOU WANT SPEED
cout << '\n';
writeGroups( groups );
}
void writeGroups( const vector< set<int> > &groups )
{
for ( auto S : groups )
{
if ( S.size() > 0 )
{
for ( int i : S ) cout << i << ' ';
cout << '\n';
}
}
}