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>
using namespace std;
using ll = long long;
const int maxn = 4e5 + 5;
int lab[maxn], deg[maxn];
int n;
int findset(int u) {
if (lab[u] == u) return u;
return lab[u] = findset(lab[u]);
}
bool join(int u, int v) {
u = findset(u); v = findset(v);
if (u == v) return false;
lab[v] = u;
return true;
}
long long plan_roller_coaster(vector<int> s, vector<int> t) {
vector<int> coor;
n = s.size();
for (int & i : s) coor.push_back(i);
for (int & i : t) coor.push_back(i);
sort(coor.begin(), coor.end());
coor.erase(unique(coor.begin(), coor.end()), coor.end());
iota(lab, lab + coor.size(), 0);
auto compv = [&](int v) {
return lower_bound(coor.begin(), coor.end(), v) - coor.begin();
};
for (int & i : s) i = compv(i);
for (int & i : t) i = compv(i);
for (int i = 0; i < n; ++i) {
++deg[s[i]];
--deg[t[i]];
join(s[i], t[i]);
}
vector<array<int, 3>> edges;
ll ret = 0;
deg[coor.size() - 1]++;
deg[0]--;
int m = coor.size();
for (int i = coor.size() - 1; i >= 1; --i) {
edges.push_back({coor[i] - coor[i - 1], i, i - 1});
if (deg[i] < 0) {
deg[i - 1]--;
join(i, i - 1);
ret += coor[i] - coor[i - 1];
deg[i]++;
//cerr << coor[i] << ' ';
} else if (deg[i] > 0) {
deg[i - 1]++;
deg[i]--;
join(i, i - 1);
}
}
for (int & i : deg) assert(i == 0);
//for (int i = 0; i < coor.size(); ++i)
//cerr << coor[i] << ' ' << deg[i] << '\n';
sort(edges.begin(), edges.end());
for (auto & it : edges) {
if (join(it[1], it[2])) {
//cerr << it[0] << ' ' << coor[it[1]] << ' ' << coor[it[2]] << '\n';
ret += it[0];
}
}
return ret;
}
#ifdef LOCAL
signed main(void) {
ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#ifdef LOCAL
freopen("A.INP", "r", stdin);
freopen("A.OUT", "w", stdout);
#endif // LOCAL
int n; cin >> n;
vector<int> s(n), t(n);
for (int & i : s) cin >> i;
for (int & i : t) cin >> i;
cout << plan_roller_coaster(s, t);
}
#endif // LOCAL
Compilation message (stderr)
railroad.cpp: In function 'long long int plan_roller_coaster(std::vector<int>, std::vector<int>)':
railroad.cpp:48:7: warning: unused variable 'm' [-Wunused-variable]
48 | int m = coor.size();
| ^
# | 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... |