1
0
Fork 0

Update graph/hierholzer.cc

Signed-off-by: subcrip <contact@subc.rip>
This commit is contained in:
subcrip 2024-09-20 15:41:11 +08:00
parent 6c0c82c022
commit 1351da1b92
1 changed files with 55 additions and 24 deletions

View File

@ -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;
} }
}; };