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>
#define fi first
#define se second
#define ssize(x) int(x.size())
#define pn printf("\n");
using namespace std;
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<int, ll> pil;
typedef pair<ll, int> pli;
typedef pair<ll, ll> pll;
int inf = 1e09; ll infll = 1e18;
struct DSU{
vector<int> rep, sz;
void init(int n){
rep.resize(n+1), sz.resize(n+1, 1);
for(int i = 1; i <= n; ++i) rep[i] = i;
} int Find(int a){
return (a != rep[a]) ? rep[a] = Find(rep[a]) : a;
} void Union(int a, int b){
a = Find(a), b = Find(b);
if(a == b) return;
if(sz[a] < sz[b]) swap(a, b);
rep[b] = a, sz[a] += sz[b];
}
} DSU;
struct edge{
int a, b; ll c;
edge(){}
edge(int A, int B, ll C) : a(A), b(B), c(C) {}
bool operator<(const edge &x) const{ return c < x.c; }
};
ll plan_roller_coaster(vector<int> s, vector<int> e){
s.emplace_back(inf+1), e.emplace_back(1); // dodatkowa stacja
int m = ssize(s), a, b; // m - ilosc stacji (poczatkowych kr. w grafie, n - ilosc wierzcholkow
set<int> sc; unordered_map<int, int> mp; int n = 0; // skalowanie
for(int i = 0; i < m; ++i) sc.emplace(s[i]), sc.emplace(e[i]);
for(int i : sc) mp[i] = ++n;
vector<int> def_val(n+1);
for(int i = 0; i < m; ++i) a = mp[s[i]], b = mp[e[i]],
def_val[a] = s[i], s[i] = a, def_val[b] = e[i], e[i] = b;
DSU.init(n);
ll result = 0;
vector<int> pf_sum(n+1); // trzymamy w tym roznice miedzy krawedziami
for(int i = 0; i < m; ++i) ++pf_sum[s[i]], --pf_sum[e[i]], DSU.Union(s[i], e[i]);
for(int i = 1; i < n; ++i){
pf_sum[i] += pf_sum[i-1];
if(pf_sum[i] > 0) result += pf_sum[i] * ll(def_val[i+1]-def_val[i]);
if(pf_sum[i]) DSU.Union(i, i+1);
}
vector<edge> MST; //MST
for(int i = 1; i < n; ++i) if(DSU.Find(i) != DSU.Find(i+1)) MST.emplace_back(i, i+1, def_val[i+1]-def_val[i]);
sort(MST.begin(), MST.end());
for(edge i : MST) if(DSU.Find(i.a) != DSU.Find(i.b)) DSU.Union(i.a, i.b), result += i.c;
return result;
}
#ifdef LOCAL
int main(){
int n; scanf("%d", &n);
vector<int> s(n), e(n);
for(int i = 0; i < n; ++i) scanf("%d%d", &s[i], &e[i]);
printf("%lld\n", plan_roller_coaster(s, e));
return 0;
}
#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... |