Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Tested by zydhanlinnar11 on May 28, 2022
- #include <iostream>
- #include <vector>
- #include <stack>
- #include <cassert>
- using namespace std;
- typedef vector<int> vi;
- typedef vector<vi> vvi;
- typedef stack<int> si;
- bool dfs(vvi &adjList, vi &state, si &vertex, int dst) {
- if(state[dst] == 1)
- return false;
- if(state[dst] == 2)
- return true;
- state[dst] = 1;
- bool ret = true;
- for(int i=0; i < adjList[dst].size() && ret; i++)
- ret &= dfs(adjList, state, vertex, adjList[dst][i]);
- state[dst] = 2;
- vertex.push(++dst);
- return ret;
- }
- bool topsort(vvi &adjList, vi &state, si &vertex, int n) {
- for(int i=0; i<n; i++)
- if(state[i] != 2 && !dfs(adjList, state, vertex, i))
- return false;
- return true;
- }
- int main() {
- #ifdef ZYD_WSL
- freopen("/home/zydhanlinnar11/prakfinal-qa/in", "r", stdin);
- #endif
- ios_base::sync_with_stdio(false); cin.tie(NULL);
- int n, m;
- cin>>n>>m;
- assert(n == (int)1e5 && m == (int)1e5);
- assert(1 <= n && n <= (int)1e5);
- assert(1 <= m && m <= (int)1e5);
- vvi adjList(n); vi state(n, 0); si vertex;
- for(int i=0; i<m; i++) {
- int src, dst;
- cin>>src>>dst;
- assert(1 <= src && src <= n);
- assert(1 <= dst && dst <= n);
- src--, dst--;
- adjList[src].push_back(dst);
- }
- if(topsort(adjList, state, vertex, n))
- for(int i=0; i<n; i++) {
- cout<<vertex.top()<<" \n"[i == n - 1];
- vertex.pop();
- }
- else cout<<"-1\n";
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement