-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind Itinerary from a given list of tickets.cpp
59 lines (53 loc) · 1.23 KB
/
Find Itinerary from a given list of tickets.cpp
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
/*
1
4
chennai banglore
bombay delhi
goa chennai
delhi goa
*/
#include<bits/stdc++.h>
using namespace std;
void findItinerary(int);
void _findItinerary(map<string, string>&, vector<pair<string, string>>);
int main(){
int t, n;
cin >> t;
while(t--){
cin >> n;
findItinerary(n);
cout << endl;
}
return 0;
}
void findItinerary(int n){
map<string, string> om;
map<string, string>::iterator it;
for(int i = 0; i < n; i++){
string a, b;
cin >> a >> b;
om[a] = b;
}
for(it = om.begin(); it != om.end(); it++){
vector<pair<string, string>> vec;
vec.push_back({it->first, it->second});
_findItinerary(om, vec);
}
}
void _findItinerary(map<string, string> &om, vector<pair<string, string>> vec){
if(vec.size() == om.size()){
cout << "[";
for(int i = 0; i < vec.size(); i++){
cout << "('" << vec[i].first << "','" << vec[i].second << "')";
}
cout << "]";
return;
}
pair<string, string> temp = vec.back();
map<string, string>::iterator it;
it = om.find(temp.second);
if(it != om.end()){
vec.push_back({it->first, it->second});
_findItinerary(om, vec);
}
}