NEW GAME

#include <bits/stdc++.h>
using namespace std;
const int N=1010;
int n,m;
int dp[N];
int d[N];
vector<int>g[N];
vector<int>ans;
void topo() // 拓扑排序
{
    priority_queue<int,vector<int>,greater<int> >q; // 编号小的在前
    while(!q.empty())
        q.pop();
    ans.clear();
    for(int i=1;i<=n;i++)
        if(!d[i])q.push(i);
    while(!q.empty())
    {
        int u=q.top();q.pop();
        ans.push_back(u);
        int sz=g[u].size();
        for(int i=0;i<sz;i++)
        {
            int v=g[u][i];
            d[v]--;
            if(d[v]==0)q.push(v);
        }
    }
}

int main()
{
    int t;
    ios::sync_with_stdio(false);
    cin>>t;
    while (t--) {
        while (cin >> n >> m) {
            for (int i = 1; i <= n; i++)
                g[i].clear();
            memset(d, 0, sizeof(d));
            int x, y;
            for (int i = 1; i <= m; i++) {
                cin >> x >> y; // 不去重边也没事,可以自己模拟一下
                g[x].push_back(y);
                d[y]++;
            }
            topo();
            for (int i = 0; i < n; i++)
                i == n - 1 ? printf("%d\n", ans[i]) : printf("%d ", ans[i]);
        }
    }
    return 0;
}
posted on 2023-03-05 15:27  IR101  阅读(7)  评论(0编辑  收藏  举报  来源