Given an unordered list of flights taken by someone, each represented as (origin, destination) pairs, and a starting airport, compute the person's itinerary. If no such itinerary exists, return null. If there are multiple possible itineraries, return the lexicographically smallest one. All flights must be used in the itinerary.
For example, given the list of flights [('SFO', 'HKO'), ('YYZ', 'SFO'), ('YUL', 'YYZ'), ('HKO', 'ORD')] and starting airport 'YUL', you should return the list ['YUL', 'YYZ', 'SFO', 'HKO', 'ORD'].
Given the list of flights [('SFO', 'COM'), ('COM', 'YYZ')] and starting airport 'COM', you should return null.
Given the list of flights [('A', 'B'), ('A', 'C'), ('B', 'C'), ('C', 'A')] and starting airport 'A', you should return the list ['A', 'B', 'C', 'A', 'C'] even though ['A', 'C', 'A', 'B', 'C'] is also a valid itinerary. However, the first one is lexicographically smaller.
Example:
Input: tickest = {{"SFO", "HKO"}, {"YYZ", "SFO"}, {"YUL", "YYZ"}, {"HKO", "ORD"}}, start="YUL"
Output: [YUL,YYZ,SFO,HKO,ORD]
Approach
C++
#include <bits/stdc++.h>using namespace std;vector<string> res;map<string, multiset<string>> ump;void fun(string x){while (ump[x].size() > 0){auto it = ump[x].begin();string y = *it;ump[x].erase(ump[x].begin());fun(y);}res.push_back(x);}vector<string> findItinerary(vector<vector<string>> &tickets,string start){for (int i = 0; i < tickets.size(); i++){string u = tickets[i][0];string v = tickets[i][1];ump[u].insert(v);}fun(start);reverse(res.begin(), res.end());return res;}int main(){vector<vector<string>> tickets = {{"SFO", "HKO"},{"YYZ", "SFO"},{"YUL", "YYZ"},{"HKO", "ORD"}};string start = "YUL";vector<string> res = findItinerary(tickets, start);cout << "[";for (int i = 0; i < res.size() - 1; i++)cout << res[i] << ",";cout << res[res.size() - 1] << "]";return 0;}
No comments:
Post a Comment