-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDgph.cpp
140 lines (112 loc) · 2.72 KB
/
Dgph.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
/*
@Chiranjeevi
Date: 6-Jul-17
*/
#include <iostream>
#include <vector>
#include <algorithm>
#include <queue>
#include <stack>
using namespace std;
struct node{
int v;
node *next;
};
node *newNode(int b){
node *temp=new node();
temp->v=b;
temp->next=NULL;
return temp;
}
void addDEdge(vector<node *> &dgph, int a, int b){
if(dgph[a]==NULL){
dgph[a]=newNode(b);
}
else{
node *ptr=dgph[a];
while(ptr->next!=NULL)
ptr=ptr->next;
ptr->next=newNode(b);
}
}
void createDGraph(vector<node *> &dgph, int E){
int a, b;
for(int i=0; i<E; i++){
cin>>a>>b;
addDEdge(dgph, a, b);
}
}
void printDGraph(vector<node *> &dgph){
int V=dgph.size();
node *ptr=NULL;
for(int i=0; i<V; i++){
ptr=dgph[i];
while(ptr!=NULL){
cout<<i<<"->"<<ptr->v<<endl;
ptr=ptr->next;
}
}
}
void DGraphDFS(int vertex, vector<node *> &dgph, bool mark[], int parent[]){
node *ptr=dgph[vertex];
mark[vertex]=true;
while(ptr!=NULL){
if(!mark[ptr->v]){
parent[ptr->v]=vertex;
DGraphDFS(ptr->v, dgph, mark, parent);
}
ptr=ptr->next;
}
}
void DGraphBFS(int vertex, vector<node *> &dgph, bool mark[], int distance[]){
int count=1;
queue<int> q;
node *ptr=NULL;
q.push(vertex);
while(!q.empty()){
ptr=dgph[q.front()];
q.pop();
while(ptr!=NULL){
if(!mark[ptr->v]){
mark[ptr->v]=true;
distance[ptr->v]=count;
q.push(ptr->v);
}
ptr=ptr->next;
}
count++;
}
}
void DgraphDFS(int vertex, vector<node *> &dgph, bool mark[], stack<int> &topo_sort){
mark[vertex]=true;
node *ptr=dgph[vertex];
while(ptr!=NULL){
if(!mark[ptr->v]){
DgraphDFS(ptr->v, dgph, mark, topo_sort);
}
ptr=ptr->next;
}
topo_sort.push(vertex);
}
void TopologicalSort(vector<node *> &dgph, bool mark[], stack<int> &topo_sort){
int V=dgph.size();
for(int i=0; i<V; i++){
if(!mark[i]){
DgraphDFS(i, dgph, mark, topo_sort);
}
}
}
int main(){
int V,E;
cin>>V>>E;
vector<node *> dgph(V, NULL);
stack<int> topo_sort;
bool mark[V] = {false};
createDGraph(dgph, E);
printDGraph(dgph);
TopologicalSort(dgph, mark, topo_sort);
while(!topo_sort.empty()){
cout<<topo_sort.top()<<"->";
topo_sort.pop();
}
}