难度:3
简单拓扑排序,输入m和n的时候要注意。不能直接输入n与m同时不为零,因为可能有几个点但是没有边的情况。
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define all(x) (x).begin(), (x).end()
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> pa;
int n, m;
int graph[105][105];
int indegree[105];
vi v;
void toposort() {
queue<int> q;
for (int i = 1; i <= n; i++) {
if (!indegree[i]) q.push(i);
}
while (!q.empty()) {
int now = q.front();
q.pop();
v.pb(now);
for (int i = 1; i <= n; i++) {
if (graph[now][i]) {
if (--indegree[i] == 0) q.push(i);
}
}
}
}
int main() {
while (cin >> n >> m && n) {
fill(graph[0], graph[0] + 105 * 105, 0);
fill(indegree, indegree + 105, 0);
for (int i = 0; i < m; i++) {
int a, b;
cin >> a >> b;
graph[a][b] = 1;
indegree[b]++;
}
toposort();
for (auto &p : v) {
cout << p << " ";
}
cout << endl;
v.clear();
}
return 0;
}