Skip to content

Commit 0b1040b

Browse files
committed
lexicographical topological sorting - Airbnb
1 parent 166b211 commit 0b1040b

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: Solution/Day-092.cpp

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
class Solution{
4+
private:
5+
set<string>id;
6+
map<string , int>in_deg;
7+
map<string , set<string>>graph;
8+
vector<string> Sort(void){
9+
vector<string>res;
10+
while(!id.empty()){
11+
string current = *(id.begin());
12+
id.erase(current);
13+
res.push_back(current);
14+
for(auto&itr:graph[current]){
15+
in_deg[itr]--;
16+
if(in_deg[itr]==0){
17+
id.insert(itr);
18+
}
19+
}
20+
}
21+
return res;
22+
}
23+
public:
24+
vector<string> topologicalSort(map<string , vector<string>>&cID){
25+
// C++ map maintain sorted already so we don't have to sort the courses
26+
// If it wasn't map then we have to first sort the course , then their pre-requisites
27+
for(auto&courses:cID){
28+
if(courses.second.size() == 0){
29+
id.insert(courses.first);
30+
}else{
31+
for(auto&itr:courses.second){
32+
graph[itr].insert(courses.first);
33+
}
34+
}
35+
in_deg[courses.first] = courses.second.size();
36+
}
37+
return Sort();
38+
}
39+
};
40+
int main(void){
41+
map<string , vector<string>> cID{
42+
{"CSC300" , {"CSC100" , "CSC200"}},
43+
{"CSC200" , {"CSC100"}},
44+
{"CSC100" , {}}
45+
};
46+
Solution s1;
47+
vector<string>v = s1.topologicalSort(cID);
48+
for(auto&itr:v){
49+
cout << itr << ' ';
50+
}
51+
cout << '\n';
52+
return 0;
53+
}

0 commit comments

Comments
 (0)