优先队列 + 反向拓扑
//#include<bits/stdc++.h> #include<iostream> #include<cstdio> #include<algorithm> #include<queue> #include<cstring> using namespace std; const int maxn = 1e5 + 7; int n, m; vector<int>G[maxn]; int inDeg[maxn]; int dp[maxn]; int cnt; int sum ,ans ; int mp[1000][1000]; bool topsort() { //queue<int>q; priority_queue<int>q; //queue<int>q; cnt = 0; sum = 0; while(!q.empty())q.pop(); for(int i = 1; i <= n ; i++) if(!inDeg[i]) q.push(i); while(!q.empty()) { int now = q.top(); q.pop(); // cout << now << endl; sum ++; dp[now] = n--; // cout << dp[now] << endl; for(int i = 0; i < G[now].size(); i++) { int to = G[now][i]; inDeg[to]--; if(!inDeg[to]) q.push(to); // dp[to] = max(dp[to],dp[now] + G[now][i].second); } } if(sum == ans)return 1; else return 0; } int main() { int t; ios::sync_with_stdio(false); cin.tie(0); cout.tie(0); // cin >> t; cin >> t; while(t--){ cin >> n >> m; ans = n; memset(inDeg,0,sizeof inDeg); memset(dp,0,sizeof dp); for(int i = 1; i <= n ; i++) G[i].clear(); while(m--) { int u, v, w; cin >> u >> v ; //if(mp[u][v] == 0) G[v].push_back(u); //G[v].push_back(make_pair((u,w))); inDeg[u] ++; } if(topsort()) //int maxx = 0; for(int i = 1; i <= ans ; i++) printf("%d%c",dp[i]," "[i == ans]); else puts("-1"); } return 0; }