-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTopSort.cpp
More file actions
35 lines (31 loc) · 754 Bytes
/
Copy pathTopSort.cpp
File metadata and controls
35 lines (31 loc) · 754 Bytes
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
#include<iostream>
#include<malloc.h>
#include<queue>
using namespace std;
int N;
struct node {
int numIn;
int numOut;
int next[101];
node (): numIn(0), numOut(0){}
};
int *topSort(node nodes[]) {
int *toReturn = (int *)malloc(N * sizeof(int));
int index = 0;
queue<int> q;
for(int i = 0; i < N; i++)
if(nodes[i].numIn == 0)
q.push(i);
while(!q.empty()){
int popped = q.front();
q.pop();
toReturn[index++] = popped;
node &curr = nodes[popped];
for(int i = 0; i < curr.numOut; i++){
node &nextNode = nodes[curr.next[i]];
nextNode.numIn--;
if(nextNode.numIn == 0)
q.push(curr.next[i]);
}
}
}