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 ll inf = 1e9+5;
const int md1 = 1e9+7;
const int md2 = 998244353;
using vi = vector<int>;
using ai = array<int, 2>;
#define sz(v) ((int)v.size())
#define pb push_back
#define pry cout << "YES\n"
#define prn cout << "NO\n"
#define endl '\n'
#define fst first
#define scn second
/* #define ONPC */
const int N = 2e5+5;
int p[N<<1];
int
lb(int x, vi& v)
{
int l = 0, r = sz(v);
int mid;
while (l < r) {
mid = (l+r)>>1;
if (v[mid] > x)
r = mid;
else
l = mid+1;
}
return l-1;
}
int
getp(int x)
{
return p[x] = (x == p[x]) ? x : getp(p[x]);
}
ll
uni(int a, int b)
{
a = getp(a);
b = getp(b);
p[a] = b;
return (a!=b);
}
ll
plan_roller_coaster(vi s, vi t)
{
int n = sz(s);
vi nm;
for (int i = 0; i < n; ++i) nm.pb(s[i]);
for (int i = 0; i < n; ++i) nm.pb(t[i]);
nm.pb(0);
nm.pb(inf);
sort(nm.begin(), nm.end());
nm.resize(distance(nm.begin(), unique(nm.begin(), nm.end())));
vi qin, qot;
int pin, pot;
pin = pot = 0;
for (int i = 0; i < sz(nm); ++i) p[i] = i;
for (int i = 0; i < n; ++i) {
qin.pb(lb(s[i],nm));
qot.pb(lb(t[i],nm));
uni(lb(s[i], nm), lb(t[i], nm));
}
uni(0, sz(nm)-1);
/* for (int i = 0; i < 20; ++i) { */
/* cout << i << ": " << lb(i, nm) << endl; */
/* } */
qot.pb(0);
sort(qin.begin(), qin.end());
sort(qot.begin(), qot.end());
ll ans = 0;
for (int i = 0; i < sz(nm)-1; ++i) {
while (pin < sz(qin)) {
if (qin[pin] > i) break;
++pin;
}
while (pot < sz(qot)) {
if (qot[pot] > i) break;
++pot;
}
if (pot < pin) {
ans += ((ll) pin-pot) * ((ll) (nm[i+1]-nm[i]));
uni(i,i+1);
} else if (pot > pin) {
uni(i,i+1);
}
}
vector<ai> edg;
for (int i = 0; i < sz(nm)-1; ++i)
edg.pb({nm[i+1]-nm[i], i});
sort(edg.begin(), edg.end());
for (int i = 0; i < sz(edg); ++i) {
ans += uni(edg[i][1], edg[i][1]+1) * ((ll)edg[i][0]);
}
return ans;
}
#ifdef ONPC
void
solve()
{
int n;
cin >> n;
vi t(n), s(n);
for (int i = 0; i < n; ++i) cin >> s[i];
for (int i = 0; i < n; ++i) cin >> t[i];
cout << plan_roller_coaster(s,t) << endl;
}
int32_t
main(int argc, char **argv)
{
if (argc >= 2) {
freopen(argv[1], "r", stdin);
} else
ios_base::sync_with_stdio(0);cin.tie(0);
int t = 1;
/* cin >> t; */
while(t--)
solve();
}
#endif
# | 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... |