-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTopological.cpp
More file actions
146 lines (126 loc) · 1.97 KB
/
Topological.cpp
File metadata and controls
146 lines (126 loc) · 1.97 KB
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
141
142
143
144
145
146
#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int indegree[n+1];
memset(indegree,0,sizeof indegree);
indegree[1]=n-1;
vector<int> graph[n+1];
for(int i=2;i<=n;i++)
{
int x;
cin>>x;
indegree[x]+=1;
graph[i].push_back(x);
}
queue<int> q;
for(int i=1;i<=n;i++)
{
if(!indegree[i])
{
q.push(i);
}
}
while(!q.empty())
{
int cur=q.front();
q.pop();
for(auto x:graph[cur])
{
indegree[x]-=1;
ans[x]+=1+ans[cur];
if(!indegree[x])
{
q.push(x);
}
}
}
template<typename T>
class MyGraph{
map<T,list<T>> adj;
public:
void addEdge(T x,T y)
{
adj[x].push_back(y);
}
void dfs_helper(T src,unordered_map<T,bool> &visited,list<T> &ordering)
{
visited[src]=true;
// cout<<src<<"R";
for(auto nbr:adj[src])
{
if(!visited[nbr])
{
dfs_helper(nbr,visited,ordering);
}
}
ordering.push_front(src);
return;
}
void topology()
{
unordered_map<T,bool> visited;
list<T> ordering;
for(auto node:adj)
{
visited[node.first]=false;
}
for(auto node:adj)
{
if(!visited[node.first])
{
dfs_helper(node.first,visited,ordering);
}
}
for(auto node:ordering)
cout<<node<<" ";
}
void topology_bfs()
{
unordered_map<T,int> indegree;
for(auto node:adj)
{
indegree[node.first]=0;
}
for(auto node:adj)
{
for(auto nbr:node.second)
{
indegree[nbr]++;
}
}
queue<T> q;
for(auto node:adj)
{
if(indegree[node.first]==0)
{
q.push(node.first);
}
}
while(!q.empty())
{
T node = q.front();
cout<<node<<" ";
q.pop();
for(auto nbr:adj[node])
{
indegree[nbr]-=1;
if(!indegree[nbr])
q.push(nbr);
}
}
}
};
int main()
{
#ifndef ONLINE_JUDGE
freopen("in.txt","r",stdin);
freopen("otpt.txt","w",stdout);
#endif
MyGraph<int> g;
g.addEdge(3, 1);
g.addEdge(2, 3);
g.addEdge(1, 2);
g.addEdge(4, 1);
g.topology();
return 0;
}