AcWing 848. 有向图的拓扑序列 C++
原题链接
简单
作者:
LaChimere
,
2021-05-27 11:01:26
,
所有人可见
,
阅读 173
C++
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int MAXSIZE = 100010;
int n, m;
vector<vector<int> > graph(MAXSIZE, vector<int>());
vector<int> inDegree(MAXSIZE, 0), topoRes;
void addEdge(int from, int to) {
graph[from].push_back(to);
++inDegree[to];
}
bool topoSort() {
queue<int> q;
for (int i = 1; i <= n; ++i) {
if (inDegree[i] == 0) {
q.push(i);
}
}
while (!q.empty()) {
int v = q.front();
q.pop();
topoRes.push_back(v);
for (int u : graph[v]) {
--inDegree[u];
if (inDegree[u] == 0) {
q.push(u);
}
}
// graph[v].clear();
}
return topoRes.size() == n;
}
int main() {
int x, y;
cin >> n >> m;
while (m--) {
cin >> x >> y;
if (x == y) {
cout << -1 << endl;
return 0;
}
addEdge(x, y);
}
if (topoSort()) {
for (int v : topoRes) {
cout << v << " ";
}
} else {
cout << -1 << endl;
}
return 0;
}