拓扑排序

拓扑排序

 

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
int n, m;

void topo(vector<int>& rec, queue<int>&q)
{
    for (int i = 1; i <= n; i++)
        if (rec[i] == 0)
        {
            q.push(i);
            rec[i] = -1;
        }
}

int main(void)
{
    while (cin >> n >> m &&( n != 0 || m != 0))
    {
        vector < vector<int>> oni(n+1);
        vector<int>rec(n+1), ans;
        rec.resize(n + 1);
        queue<int> toposort;
        for (int i = 0; i < m; i++)
        {
            int a, b; cin >> a >> b;
            rec[b]++;
            oni[a].push_back(b);
        }
        topo(rec, toposort);
        while (!toposort.empty())
        {
            int t = toposort.front(); toposort.pop(); ans.push_back(t);
            for (int v : oni[t])rec[v]--;
            topo(rec, toposort);
        }
        for (int i = 0; i < ans.size(); i++)
        {
            printf("%d%s", ans[i], i == ans.size() - 1 ? "\n" : " ");
        }
    }
}

 

上一篇:qrc文件使用


下一篇:利用MeterSphere实现高级断言实践