Strongly Connected Component
Author : Md.Saiful Islam
***/
#include<iostream>
#include<vector>
#define sz 10001
using namespace std;
vector<int>adj[sz];
int Node,Edge,u,v,array[sz],top,r;
bool Flag[sz];
void DFS(int u,bool s)
{
if(Flag[u] == s) return;
Flag[u]= s;
for(int i=0;i<adj[u].size();i++)
DFS(adj[u][i],s);
if(s) array[top--]=u;
return;
}
int main()
{
int i,j,test,cnt,kase=1;
scanf("%d",&test);
while(test--)
{
scanf("%d %d",&Node,&Edge);
for(i=1;i<=Edge;i++)
{
scanf("%d %d",&u,&v);
adj[u].push_back(v);
}
top=Node; cnt=0;
for(i=1;i<=Node;i++)
if(!Flag[i])
DFS(i,true);
for(i=1;i<=Node;i++)
{
if( Flag[ array[i] ] )
{
DFS( array[i] , false );
cnt++;
}
adj[ array[i] ].clear();
}
printf("Case %d: %d\n",kase++,cnt);
for(i=0;i<=Node;i++)Flag[i] = false;
}
return 0;
}
/*
Input:
3
5 4
1 2
1 3
3 4
5 3
4 4
1 2
1 3
4 2
4 3
3 2
1 2
2 3
Output:
Case 1: 2
Case 2: 2
Case 3: 1
*/
No comments:
Post a Comment