#### 思路

``````const int N = 1e5 + 10;//数据范围，一般边数组要比点数组多开一倍空间
int n, m;//点数和边数
int h[N], e[N], ne[N], idx = 0;

{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);//记得初始化h数组，不然会TLE
for(int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
}
}
``````

#### 代码

``````#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, m;
int h[N], e[N], ne[N], idx = 0;
int d[N];
queue<int> q, res;
{
e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}
bool topsort()
{
for(int i = 1; i <= n; i++)
{
if(d[i] == 0) q.push(i);
}
while(q.size())
{
auto t = q.front();res.push(t);q.pop();

for(int i = h[t]; i != -1; i = ne[i])
{
int j = e[i];
d[j]--;
if(d[j] == 0) q.push(j);
}
}
if(res.size() == n) return true;
else return false;
}
int main()
{
cin >> n >> m;
memset(h, -1, sizeof h);
for(int i = 0; i < m; i++)
{
int a, b;
cin >> a >> b;
d[b]++;
}

if(topsort())
{
while(res.size())
{
cout << res.front() <<  " ";
res.pop();
}
puts("");
}
else puts("-1");

return 0;
}
``````