拓扑排序 HDU1285

这个题是个模板题,可以直接用拓扑排序的模板来做,

AC代码

#include <stdio.h>
#include<iostream>
#include <string.h>
using namespace std;
const int N = 1000;
int n, m;
int Map[N][N];
int topNum[N];
bool toposort(int *ret)
{
    int Indegree[N];
    memset(Indegree, 0, sizeof(Indegree));
    int k = 0;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= n; j++)
            Indegree[i] += Map[j][i];//计算入度,没有边的时候Map[j][i]为0
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (Indegree[j] == 0)
            {
                --Indegree[j];
                ret[k++] = j;
                for (int t = 1; t <= n; t++)
                    if (Map[j][t])
                        Indegree[t]--;
                break;
            }
        }   
            
    }
    if (k == n)
        return true;
    return false;
}
int main()
{
    int a, b;
    while (cin >> n >> m)
    {
        memset(Map, 0, sizeof(Map));
        for (int i = 0; i < m; i++)
        {
            cin >> a >> b;
            Map[a][b] = 1;
        }
        toposort(topNum);   
        for (int i = 0; i < n; i++)
        {
            if (i == n - 1)
                printf("%d\n", topNum[i]);
            else
                printf("%d ", topNum[i]);
        }
    }
    

    return 0;
}
View Code

 

posted @ 2015-03-27 21:47  Howe_Young  阅读(146)  评论(0编辑  收藏  举报