输入样例:
3 3
1 2
2 3
1 3
输出样例:
1 2 3
#include<bits/stdc++.h>
using namespace std;
const int N = 1e6 + 10;
int h[N], ne[N], e[N], idx;//邻接表存储图
int in[N];
int q[N], tt = -1,hh=0;
int n, m;
void add(int a, int b) {
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
void topology() {
for (int i = 1;i <= n;i++) {
if (in[i] == 0) {
q[++tt] = i;
}
}
while (hh <= tt) {
int now = q[hh++];
for (int i = h[now];i != -1;i = ne[i]) {
int j = e[i];
in[j]--;
if (in[j] == 0) {
q[++tt] = j;
}
}
}
if (tt == n - 1) {
for (int i = 0;i <= tt;i++) {
cout << q[i] << ' ';
}
}
else cout << -1;
}
int main() {
cin >> n >> m;
memset(h, -1, sizeof h);
for (int i = 0;i < m;i++) {
int a, b;
cin >> a >> b;
add(a, b);
in[b]++;
}
topology();
return 0;
}