It is a simple topological sort problem, I am getting runtime error on hidden test cases, visible test cases are returning the right answer. This is my code.
#include
#include <bits/stdc++.h>
using namespace std;
class graph{
int n;
map<string,list> adjlist;
map<string,bool> visited;
stack s;
vector order;
stack sr;
public :
graph(int v){
n=v;
}
void Addorder(string a){
order.push_back(a);
}
void AddEdge(string a,string b){
adjlist[a].push_back(b);
visited[a]=0;
//order.push_back(a);
}
void DFS(string a){
if(visited[a]==0){
visited[a]=1;
for(auto child : adjlist[a]){
if(visited[child]==0){
DFS(child);
}
}
s.push(a);
}
}
void orderDFS(){
for(int i=order.size()-1;i>=0;i--){
if(visited[order[i]]==0){
DFS(order[i]);
/*while(!s.empty()){
sr.push(s.top());
s.pop();
}*/
}
}
}
void printStack(){
while(!s.empty()){
cout<<s.top()<<" ";
s.pop();
}
}
};
int main() {
int t;
cin>>t;
for(int i=1;i<=t;i++){
string temp,temp1,temp2;
int n,m;
cin>>n;
graph g(n);
while(n–){
cin>>temp;
g.Addorder(temp);
}
cin>>m;
while(m–){
cin>>temp1>>temp2;
g.AddEdge(temp1,temp2);
}
getline(cin,temp);
g.orderDFS();
cout<<“Case #”<<i<<": Vivek should drink beverages in this order: ";
g.printStack();
cout<<endl;
}
return 0;
}