码迷,mamicode.com
首页 > 编程语言 > 详细

拓扑排序

时间:2017-10-30 21:04:47      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:--   return   std   拓扑排序   nbsp   str   ons   cst   ++   

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<queue>
using namespace std;
const int maxn=50010;
int first[maxn],to[maxn],next[maxn],cnt;
inline int read()
{
    int x=0,f=1;
    char ch=getchar();
    while(!isdigit(ch)){if(ch==-)f=-1;ch=getchar();}
    while(isdigit(ch)){x=10*x+ch-0;ch=getchar();}
    return x*f;
}
void add(int u,int v)
{
    to[++cnt]=v;
    next[cnt]=first[u];
    first[u]=cnt;
}
queue<int> q;
int rd[maxn];
int toposort[maxn];
int main()
{
    int n,m;
    n=read(),m=read();
    for(int i=1;i<=m;i++)
    {
        int u,v;
        u=read(),v=read();
        add(u,v);
        rd[v]++;
    }
    int now,cnt=0;
    for(int i=1;i<=n;i++)if(!rd[i])q.push(i);
    while(!q.empty())
    {
        now=q.front();
        q.pop();
        toposort[++cnt]=now;
        for(int i=first[now];i;i=next[i])
        {
            rd[to[i]]--;
            if(!rd[to[i]])q.push(to[i]);
        }
    }
    for(int i=1;i<=cnt;i++)cout<<toposort[i]<<" ";
    cout<<endl;
    return 0;
}

 

拓扑排序

标签:--   return   std   拓扑排序   nbsp   str   ons   cst   ++   

原文地址:http://www.cnblogs.com/Kong-Ruo/p/7756311.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!