邻接矩阵
#include <iostream>
#include <queue>
#include <algorithm>
#include <set>
using namespace std;
int n, m;
vector<int> topsort(vector<int>& inDegree, vector<vector<int>>& adj)
{
queue<int> q;
for(int i = 1; i < inDegree.size(); i++)
if(!inDegree[i]) q.push(i);
vector<int> res;
while(!q.empty())
{
int cur = q.front();
q.pop();
res.push_back(cur);
for(int i = 1; i <= n; i++)
{
if(adj[cur][i])
{
inDegree[i]--;
if(inDegree[i] == 0) q.push(i);
}
}
}
return res.size() == n ? res : vector<int>();
}
int main()
{
cin >> n >> m;
vector<int> inDegree(n + 1, 0);
vector<vector<int>> adj(n + 1, vector<int>(n + 1, 0));
set<pair<int, int>> s;
for(int i = 1; i <= m; i++)
{
int a, b;
cin >> a >> b;
adj[a][b] = 1;
s.insert({a, b});
}
for(auto tmp : s)
inDegree[tmp.second]++;
vector<int> res = topsort(inDegree, adj);
if(res.empty())
{
cout << -1 << endl;
return 0;
}
for(auto & x : res)
cout << x << " ";
cout << endl;
return 0;
}
邻接表
class Solution {
public:
bool canFinish(int numCourses, vector<vector<int>>& prerequisites) {
vector<vector<int> > adj(numCourses);
vector<int> inDrgree(numCourses, 0);
for(auto tmp : prerequisites)
{
adj[tmp[1]].push_back(tmp[0]);
inDrgree[tmp[0]]++;
}
return topsort(inDrgree, adj);
}
bool topsort(vector<int>& inDrgree, vector<vector<int>> &adj)
{
queue<int> q;
for(int i = 0; i < inDrgree.size(); i++)
if(inDrgree[i] == 0) q.push(i);
int cnt = 0;
while(!q.empty())
{
int cur = q.front();
q.pop();
cnt++;
for(auto &x : adj[cur])
{
inDrgree[x]--;
if(inDrgree[x] == 0) q.push(x);
}
}
return cnt == inDrgree.size();
}
};