-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFind Itinerary.cpp
More file actions
54 lines (47 loc) · 1.36 KB
/
Copy pathFind Itinerary.cpp
File metadata and controls
54 lines (47 loc) · 1.36 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
/*
Given a list of tickets, find itinerary in order using the given list.
Example:
Input:
"Chennai" -> "Banglore"
"Bombay" -> "Delhi"
"Goa" -> "Chennai"
"Delhi" -> "Goa"
Output:
Bombay->Delhi, Delhi->Goa, Goa->Chennai, Chennai->Banglore,
*/
#include<bits/stdc++.h>
using namespace std;
bool findItinerary(unordered_map<string, string>&, unordered_map<string, string>::iterator, vector<pair<string, string>>, int);
int main(){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
unordered_map<string, string> um;
int n;
string s1, s2;
vector<pair<string, string>> vec;
cin >> n;
for(int i = 0; i < n; i++){
cin >> s1 >> s2;
um[s1] = s2;
}
for(auto it = um.begin(); it != um.end(); it++){
if(findItinerary(um, it, vec, n))
return 0;
}
cout << "Not Exist" << endl;
return 0;
}
bool findItinerary(unordered_map<string, string> &um, unordered_map<string, string>::iterator it, vector<pair<string, string>> vec, int n){
vec.push_back({it->first, it->second});
if(vec.size() == n){
for(auto itr = vec.begin(); itr != vec.end(); itr++)
cout << itr->first << "-->" << itr->second << ", ";
cout << endl;
return true;
}
auto temp = um.find(it->second);
if(temp != um.end()){
return findItinerary(um, temp, vec, n);
}
return false;
}