拓扑排序 Problem A: 有向无环图的拓扑排序

>>>>>>题目地址<<<<<<

  • code: 按题中要求用栈拓扑排序
#include <bits/stdc++.h>
using namespace std;
const int maxn = 110;
int G[maxn][maxn], inD[maxn];
bool vis[maxn];

void TopologicalSort(int n)
{
    stack<int> q;
    vector<int> ans;
    for(int i = 0; i < n; ++i)
    {
        if(inD[i] == 0)
        {
            q.push(i);
        }
    }
    while(!q.empty())
    {
        int now = q.top();
        ans.push_back(now);
        q.pop();
        vis[now] = true;
        for(int i = 0; i < n; ++i)
        {
            if(vis[i] == false && G[now][i] == 1)
            {
                inD[i]--;
                if(inD[i] == 0)
                {
                    q.push(i);
                }
            }
        }
    }
    if(ans.size() != n) printf("ERROR");
    else
    {
        for(int i = 0; i < ans.size(); ++i)
        {
            printf("%d", ans[i]);
            if(i < ans.size()-1) printf(" ");
        }
    }
    printf("\n");
}

int main()
{
    int n;
    scanf("%d", &n);
    for(int i = 0; i < n; ++i)
    {
        for(int j = 0; j < n; ++j)
        {
            scanf("%d", &G[i][j]);
            if(G[i][j] != 0) inD[j]++;
        }
    }
    TopologicalSort(n);
    return 0;
}

发布了316 篇原创文章 · 获赞 5 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_42347617/article/details/104865595