大佬帮帮我
查看原帖
大佬帮帮我
670533
spontenious楼主2023/9/17 18:09
#include <iostream>
#include <queue>
#include <stdio.h>
#include <vector>
using namespace std;
const int maxn = 105;
queue<int> mq;
int n, m;
int cnt = 0;
vector<int> g[maxn];
int indegree[maxn];
void topoSort()
{
    while (!mq.empty())
    {
        int t = mq.front();
        mq.pop();
        if (++cnt == 1)
            cout << t;
        else
            cout << " " << t;
        for (int i = 0; i < g[t].size(); i++)
        {
            indegree[g[t][i]]--;
            if (indegree[g[t][i]] == 0)
                mq.push(g[t][i]);
        }
    }
    cout << endl;
}

void init()
{
    for (int i = 1; i <= m; i++)
    {
        int a, b;
        cin >> a >> b;
        indegree[b]++;
        g[a].push_back(b);
    }
    for (int i = 1; i <= n; i++)
    {
        if (indegree[i] == 0)
            mq.push(i);
    }
}

void clean()
{
    cnt = 0;
    for (int i = 1; i < maxn;i++)
    {
        g[i].clear();
    }
}
int main()
{
    while (cin >> n >> m && (n != 0 && m != 0))
    {
        init();
        topoSort();
        clean();
    }
}
2023/9/17 18:09
加载中...