This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
struct Dsu {
std::map <int, int> p;
inline int find(int v) {
return p.find(v) == p.end() || v == p[v] ? (p[v] = v) : (p[v] = find(p[v]));
}
inline bool unite(int u, int v) {
if ((u = find(u)) == (v = find(v))) {
return false;
}
p[u] = v;
return true;
}
};
std::vector <std::pair <int, int>> edv;
std::vector <int> edw;
std::vector <int> edi;
int MST(Dsu& dsu) {
long long res = 0;
for (int x : edi) {
res += edw[x] * dsu.unite(edv[x].first, edv[x].second);
}
return res;
}
long long plan_roller_coaster(std::vector <int> s, std::vector <int> t) {
int n = s.size();
Dsu dsu;
std::vector <std::pair <long long, long long>> ts(n << 1);
for (int i = 0; i < n; i++) {
dsu.unite(s[i], t[i]);
ts[i * 2 + 0] = { s[i], 1 };
ts[i * 2 + 1] = { t[i], -1 };
}
std::sort(ts.begin(), ts.end());
long long ans = 0, is = -1;
for (int i = 0; i < (n << 1) - 1; i++) {
ans += std::max(0LL, (is += ts[i].second) * (ts[i + 1].first - ts[i].first));
if (is) {
dsu.unite(ts[i].first, ts[i + 1].first);
} else {
edw.push_back(ts[i + 1].first - ts[i].first);
edv.emplace_back(ts[i].first, ts[i + 1].first);
}
}
edi.resize(edw.size());
std::iota(edi.begin(), edi.end(), 0);
std::sort(edi.begin(), edi.end(), [&] (int u, int v) -> bool { return edw[u] < edw[v]; });
return ans + MST(dsu);
}
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |