采用广度优先遍历
有个坑,最后必须不能有空白符' ',否则会算错误

#include <iostream>
#include <vector>
#include <queue>
using namespace std;

int main()
{
    int n,m;
    cin >> n >> m;
    vector<bool> marked(n + 1,false);
    vector<int> in(n + 1, 0);
    vector<vector<int>> out(n + 1);
    for(int i = 0; i < m; ++i)
    {
        int from, to;
        cin >> from;
        cin >> to;
        out[from].push_back(to);
        ++in[to];
    }
    queue<int> wait;
    vector<int> res;
    for(int v = 1; v <= n; ++v)
    {
        if(in[v] == 0)  wait.push(v);
    }
    while(!wait.empty())
    {
        int v = wait.front();
        wait.pop();
        res.push_back(v);
        for(auto u : out[v])
        {
            if(--in[u] == 0)  wait.push(u);
        }
    }
    if(res.size() == n)
    {
        for(int i = 0; i < n; ++i)
        {
            cout << res[i];
            if(i != n - 1) cout << ' ';
        }
    }
    else
    {
        cout << -1;
    }
}