Topological Sort With Back Edge Or Cycle
Author : Md.Saiful Islam
***/
#include<stdio.h>
#include<vector>
#define mm 100000
using namespace std;
long ff,k,Node,Edge,a,b,x,aa[mm],flag[mm], tag;
vector< long >adjlist[mm];
void dfs_visit(long x)
{
long i;
flag[x] = 1;
for(i = 0; i < adjlist[x].size(); i++)
{
ff=adjlist[x].at(i);
if(flag[ff] == 0)
dfs_visit(adjlist[x][i]);
else if(flag[ff] == 1)
tag = 1;
}
aa[k++] = x;
flag[x] = 2;
}
int main()
{
long i;
while(scanf("%ld %ld",&Node,&Edge)==2 && (Node || Edge))
{
for(i=0;i<Node;i++)
{
flag[i] =0;
adjlist[i].clear();
}
for(i=0;i<Edge;i++)
{
scanf("%ld %ld",&a,&b);
adjlist[a-1].push_back(b-1);
}
tag = 0; k=0;
for(i = 0;i < Node; i++)
{
if(flag[i] == 0)
dfs_visit(i);
}
if(tag == 1)
{
printf("IMPOSSIBLE\n");
continue;
}
else
{
for(i=k-1;i>=0;i--)
printf("%ld\n",aa[i]+1);
}
}
return 0;
}
No comments:
Post a Comment