1.有向无环图,输出要求为:前一个节点必须直接或者间接指向后一个节点
#include <iostream>
#include <list>
#include <stack>
#include <string.h>
#include <stdio.h>
using namespace std;
class G
{
int v;
list<int> *adj;
void topological_Sort_Util(int v,bool visited[],stack<int> &Stack);
public:
G(int v);
void addedge(int v,int w);
void topological_Sort();
};
G::G(int v)
{
this->v=v;
adj=new list<int>[v];
}
void G::addedge(int v,int w)
{
adj[v].push_back(w);
}
void G::topological_Sort_Util(int v,bool visited[],stack<int> &Stack)
{
visited[v]=true;
list<int>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();++i)
if(!visited[*i]) topological_Sort_Util(*i,visited,Stack);
Stack.push(v);
}
void G::topological_Sort()
{
stack<int> Stack;
bool *visited=new bool[v];
memset(visited,0,sizeof(visited));
for(int i=0;i<v;i++)
if(visited[i]==false)
topological_Sort_Util(i,visited,Stack);
int t=0;
while(!Stack.empty())
{
int tmp=Stack.top();
if(tmp && t!=0)
cout<<" "<<tmp;
else if(tmp && t==0)
cout<<tmp;
t++;
Stack.pop();
}
cout<<endl;
}
int main()
{
//freopen("debug\\in.txt","r",stdin);
//freopen("debug\\out.txt","w",stdout);
int m,n;
while(cin>>n>>m && !(n==0 && m==0))
{
if(m==0)
{
for(int i=1;i<=n;i++)
{
if(i==1) cout<<i;
else cout<<" "<<i;
}
cout<<endl;
}
else
{
G g(n+1);
int a,b;
for(int i=0;i<m;i++)
{
cin>>a>>b;
g.addedge(a,b);
}
g.topological_Sort();
}
}
return 0;
}
/*
5 4
1 2
2 3
1 3
1 5
0 0
1 4 2 5 3(Special Judge)