SGU 230. Weighings (拓扑排序)

时间:2023-03-08 23:34:03
SGU 230. Weighings (拓扑排序)

题意:

给出质量为1~n的n个箱子的m对轻重关系,输出一种可能的箱子的质量排列。


Solution:

拓扑排序,注意要处理重边。

#include <iostream>
#include <queue>
using namespace std; const int N = ; queue<int> q;
bool G[N][N];
int deg[N], ans[N];
int n, m; int main()
{
ios::sync_with_stdio ();
cin >> n >> m;
for (int i = , u, v; i <= m; ++i) {
cin >> u >> v;
if(!G[u][v]){
G[u][v]=;
deg[v]++;
}
}
for (int i = ; i <= n; i++) {
if (deg[i]==) q.push (i);
}
int now = ;
while (!q.empty() ) {
int u = q.front(); q.pop();
ans[u] = ++now;
for (int i = ; i <= n; i++) {
if (G[u][i] && (--deg[i]) == ) {
q.push (i);
}
}
}
if (now == n) {
for (int i = ; i <= n; i++)
cout << ans[i] << ' ';
}
else {
cout << "No solution\n";
}
return ;
}