Update graph/hierholzer.cc
Signed-off-by: subcrip <contact@subc.rip>
This commit is contained in:
parent
6c0c82c022
commit
1351da1b92
|
@ -1,32 +1,63 @@
|
||||||
/**
|
struct hierholzer {
|
||||||
* 作者:力扣官方题解
|
struct edge_t {
|
||||||
* 链接:https://leetcode.cn/problems/reconstruct-itinerary/solutions/
|
int from, to, rev, stale;
|
||||||
* 来源:力扣(LeetCode)
|
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 {
|
hierholzer(int n) : n(n), ch(n + 1), qu(n + 1) {}
|
||||||
public:
|
|
||||||
unordered_map<string, priority_queue<string, vector<string>, std::greater<string>>> vec;
|
|
||||||
|
|
||||||
vector<string> stk;
|
void add_edge(int u, int v) {
|
||||||
|
int left = edges.size(), right = left + 1;
|
||||||
void dfs(const string& curr) {
|
edges.emplace_back(u, v, right, false);
|
||||||
while (vec.count(curr) && vec[curr].size() > 0) {
|
edges.emplace_back(v, u, left, false);
|
||||||
string tmp = vec[curr].top();
|
ch[u].emplace_back(left);
|
||||||
vec[curr].pop();
|
ch[v].emplace_back(right);
|
||||||
dfs(move(tmp));
|
qu.merge(u, v);
|
||||||
}
|
|
||||||
stk.emplace_back(curr);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
vector<string> findItinerary(vector<vector<string>>& tickets) {
|
optional<vector<int>> solve() {
|
||||||
for (auto& it : tickets) {
|
if (qu.query_size(1) != n) {
|
||||||
vec[it[0]].emplace(it[1]);
|
return nullopt;
|
||||||
}
|
}
|
||||||
dfs("JFK");
|
|
||||||
|
|
||||||
reverse(stk.begin(), stk.end());
|
int odd = 0;
|
||||||
return stk;
|
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