hdu 5154 拓扑排序

简单的拓扑排序

#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#define MAX 20007
#define MAXN 107

using namespace std;

struct 
{
    int v,next;
}e[MAX];

int in[MAXN];
int cc;
int head[MAXN];

void add ( int u  , int v )
{
    e[cc].v = v;
    e[cc].next = head[u];
    head[u] = cc++;
}

bool used[MAXN];

int main ( )
{
    int n,m,u,v;
    while ( ~scanf ( "%d%d" , &n , &m ) )
    {
        memset ( used , 0 , sizeof ( used ) );
        memset ( in , 0 , sizeof ( in ) );
        memset ( head , -1 , sizeof ( head));
        cc = 0;
        for ( int i = 0 ; i < m ; i++ )
        {
            scanf ( "%d%d" , &u , &v );
            add  ( v , u );
            in[u]++;
        }
        bool flag= true;
        int cnt = 0;
        while ( flag )
        {
            flag = false;
            for ( int i = 1 ; i <= n ; i++ )
            {
                if ( used[i] ) continue;
                if ( in[i] ) continue;
                used[i] = 1;
                flag = true;
                cnt++;
                for ( int j = head[i] ; j != -1 ; j=e[j].next )
                    in[e[j].v]--;
            } 
        }
        if ( cnt == n ) puts("YES");
        else puts ( "NO" );
    }
}

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/qq_24451605/article/details/43093363
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞