hdu 5154 拓扑排序

时间:2021-09-23 22:08:18
简单的拓扑排序
#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" );
    }
}