Update graph/hierholzer.cc
Signed-off-by: subcrip <contact@subc.rip>
This commit is contained in:
parent
6c0c82c022
commit
1351da1b92
|
@ -1,32 +1,63 @@
|
|||
/**
|
||||
* 作者:力扣官方题解
|
||||
* 链接:https://leetcode.cn/problems/reconstruct-itinerary/solutions/
|
||||
* 来源:力扣(LeetCode)
|
||||
* 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
|
||||
*/
|
||||
struct hierholzer {
|
||||
struct edge_t {
|
||||
int from, to, rev, stale;
|
||||
edge_t(int from, int to, int rev, int stale) : from(from), to(to), rev(rev), stale(stale) {}
|
||||
};
|
||||
int n;
|
||||
vector<edge_t> edges;
|
||||
vector<vector<int>> ch;
|
||||
quick_union qu;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
unordered_map<string, priority_queue<string, vector<string>, std::greater<string>>> vec;
|
||||
hierholzer(int n) : n(n), ch(n + 1), qu(n + 1) {}
|
||||
|
||||
vector<string> stk;
|
||||
|
||||
void dfs(const string& curr) {
|
||||
while (vec.count(curr) && vec[curr].size() > 0) {
|
||||
string tmp = vec[curr].top();
|
||||
vec[curr].pop();
|
||||
dfs(move(tmp));
|
||||
}
|
||||
stk.emplace_back(curr);
|
||||
void add_edge(int u, int v) {
|
||||
int left = edges.size(), right = left + 1;
|
||||
edges.emplace_back(u, v, right, false);
|
||||
edges.emplace_back(v, u, left, false);
|
||||
ch[u].emplace_back(left);
|
||||
ch[v].emplace_back(right);
|
||||
qu.merge(u, v);
|
||||
}
|
||||
|
||||
vector<string> findItinerary(vector<vector<string>>& tickets) {
|
||||
for (auto& it : tickets) {
|
||||
vec[it[0]].emplace(it[1]);
|
||||
optional<vector<int>> solve() {
|
||||
if (qu.query_size(1) != n) {
|
||||
return nullopt;
|
||||
}
|
||||
dfs("JFK");
|
||||
|
||||
reverse(stk.begin(), stk.end());
|
||||
return stk;
|
||||
int odd = 0;
|
||||
int last_odd;
|
||||
for (int i = 1; i <= n; ++i) {
|
||||
if (ch[i].size() % 2) {
|
||||
odd += 1;
|
||||
last_odd = i;
|
||||
}
|
||||
}
|
||||
|
||||
int start;
|
||||
if (odd == 0) {
|
||||
start = 1;
|
||||
} else if (odd == 2) {
|
||||
start = last_odd;
|
||||
} else {
|
||||
return nullopt;
|
||||
}
|
||||
|
||||
vector<int> res;
|
||||
|
||||
auto dfs = [&] (auto&& dfs, int v) -> void {
|
||||
while (ch[v].size()) {
|
||||
int i = ch[v].back();
|
||||
ch[v].pop_back();
|
||||
if (not edges[i].stale) {
|
||||
edges[i].stale = true;
|
||||
edges[edges[i].rev].stale = true;
|
||||
dfs(dfs, edges[i].to);
|
||||
}
|
||||
}
|
||||
res.emplace_back(v);
|
||||
};
|
||||
dfs(dfs, start);
|
||||
|
||||
return res;
|
||||
}
|
||||
};
|
||||
|
|
Loading…
Reference in New Issue