给大家写一种用字典和vector 记录边和入度信息的写法,感觉自己不太适应写一个很大的数组来记的写法
C++ 代码
#include<iostream>
#include<unordered_map>
#include<vector>
#include<queue>
using namespace std;
int main(){
int m,n,node;
cin >> n >> m;
unordered_map<int,int> indegree;
unordered_map<int,vector<int>> pre;
vector<int> res;
for (int i=0;i<m;i++)
{
int x,y;
cin >> x >> y;
indegree[y] +=1;
pre[x].push_back(y);
}
queue<int> q;
for(int i=1;i<=n;i++)
{
if (!indegree.count(i))
{
indegree[i] = 0;
q.push(i);
}
}
while(q.size())
{
node = q.front();
res.push_back(node);
q.pop();
for (auto neighbor:pre[node])
{
indegree[neighbor]--;
if (indegree[neighbor]==0) q.push(neighbor);
}
}
if (res.size()!=n) cout << -1;
else{
for (int i=0;i<res.size();i++)
{
cout << res[i] << ' ';
}
}
return 0;
}
jcnb