UVa10305 Ordering Tasks(拓扑排序水题)

这道题很显然是拓扑排序,很水的题。一种是dfs方法,另一种是不用dfs

代码如下:

dfs:

#include <cstdio>
#include <cstring>

const int N = 110;
int n, m, c[N], topo[N], t, map[N][N];
bool dfs(int u) {
    c[u] = -1;
    for ( int v = 1; v <= n; ++v ) if( map[u][v] ) {
        if ( c[v] < 0 ) return false;
        else if ( !c[v] && !dfs(v) ) return false;
    }
    c[u] = 1, topo[--t] = u;
    return true;
}
void toposort() {
    t = n; 
    for ( int u = 1; u <= n; ++u ) if ( !c[u] ) dfs(u);
}
int main()
{
    while ( scanf("%d%d", &n, &m) != EOF && !( !m && !n) ) {
        memset( map, 0, sizeof(map) );
        memset( c, 0, sizeof(c) );
        while ( m-- ) {
            int a, b;
            scanf("%d%d", &a, &b);
            map[a][b] = 1;
        }
        toposort();
        printf("%d", topo[0]);
        for ( int i = 1; i < n; ++i ) printf(" %d", topo[i]);
        printf("\n");
    }
}

非dfs:

#include <cstdio>
#include <cstring>
const int N = 110;
int n, m, id, map[N][N];
bool vis[N];
int tofind() {
    for ( int i = 1; i <= n; ++i ) {
        if ( !vis[i] ) {
            bool f = true;
            for ( int j = 1; j <= n; ++j ) {
                if (map[j][i]) {
                    f = false;
                    break;
                }
            }
            if ( f ) return i;
        }
    }
    return 0;
}
int main()
{
    while ( scanf("%d%d", &n, &m) != EOF && !( m == 0 && n == 0 ) ) {
        memset( map, 0, sizeof(map));
        memset( vis, 0, sizeof(vis));
        while ( m-- ) {
            int a, b;
            scanf("%d%d", &a, &b);
            map[a][b] = 1;
        }
        int o = 0;
        while( 1 ) {
            id = tofind();
            if ( !id ) break;
            if ( o > 0 ) printf(" ");
            printf("%d", id);
            vis[id] = true;
            ++o;
            for ( int i = 1; i <= n; ++i ) map[id][i] = 0;
        }
        printf("\n"); 
    }
}



你可能感兴趣的:(UVa10305 Ordering Tasks(拓扑排序水题))