数据结构总结之拓扑排序

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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值