高级农民
- 积分
- 1137
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-10-19
- 最后登录
- 1970-1-1
|
- // Amazon OA
- // fullfil the maximum number of moving requests
- // ["alex", 1, 2] --- alex wants to move from blg-1 to blg-2
- // ["ben", 2, 1] --- ben wants to move from blg-2 to blg-1
- typedef map<int, vector<pair<int, string>>> t_g;
- void dfs(t_g& g, pair<int, string>& e, int target, unordered_set<string>& visited, vector<pair<int, string>>& cur, vector<pair<int, string>>& longest) {
- if (visited.find(to_string(e.first) + e.second) != visited.end()) return;
- cur.push_back(e), visited.insert(to_string(e.first) + e.second);
- if (e.first == target) {
- if (cur.size() > longest.size()) longest = cur; // keep the longest, will mark visited later
- } else {
- for (auto& n : g[e.first]) {
- dfs(g, n, target, visited, cur, longest); // brute-froce try every cycle
- }
- }
- cur.pop_back(), visited.erase(to_string(e.first) + e.second);
- }
- vector<vector<string>> maxMoivingRequest(vector<vector<string>>& requests) {
- t_g g;
- for (auto& r : requests) g[stoi(r[1])].push_back({stoi(r[2]), r[0]});
-
- vector<vector<string>> ans;
- unordered_set<string> visited;
- for (auto& kv : g) {
- for (auto& e : kv.second) {
- auto start = to_string(e.first) + e.second;
- if (visited.find(start) != visited.end()) continue;
- vector<pair<int, string>> path, longest;
- dfs(g, e, kv.first, visited, path, longest);
- if (!longest.empty()) {
- ans.push_back(vector<string>{});
- for (auto& e : longest) {
- visited.insert(to_string(e.first) + e.second), ans.back().push_back(e.second);
- }
- }
- }
- }
- return ans;
- }
复制代码
这题啰嗦的地方是找出最长的环,贴一个暴力DFS的解法O(VE)time,没有仔细测试,请大伙指正。
补充内容 (2019-6-29 12:00):
发现我这个方法有一个case没有考虑到,忽略吧 |
|