Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #include <stack>
- //#include <bits/stdc++.h>
- using namespace std;
- int n, m;
- vector<int>graph[3005];
- vector<int>rev_graph[3005];
- bool visited[3005];
- stack<int>s;
- void dfs(int node){
- visited[node]=true;
- for(int i=0; i<graph[node].size(); i++){
- int sosed=graph[node][i];
- if(!visited[sosed]){
- dfs(sosed);
- }
- }
- s.push(node);
- }
- void rev_dfs(int node){
- visited[node]=true;
- cout<<node<<" ";
- for(int i=0; i<rev_graph[node].size(); i++){
- int rev_sosed=rev_graph[node][i];
- if(!visited[rev_sosed]){
- rev_dfs(rev_sosed);
- }
- }
- }
- int main()
- {
- cin>>n>>m;
- for(int i=0; i<m; i++){
- int a, b;
- cin>>a>>b;
- a--;
- b--;
- graph[a].push_back(b);
- rev_graph[b].push_back(a);
- }
- memset(visited, false, sizeof visited);
- for(int i=0; i<n; i++){
- if(!visited[i]){
- dfs(i);
- }
- }
- memset(visited, false, sizeof visited);
- while(!s.empty()){
- int node=s.top();
- // cout << node << endl;
- if(!visited[node]){
- rev_dfs(node);
- cout<<endl;
- }
- s.pop();
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement