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>
#include "railroad.h"
using namespace std;
typedef long long ll;
ll plan_roller_coaster(vector<int> s,vector<int> t)
{
int n=s.size();
s.push_back((1<<30));
t.push_back(0);
vector<array<int,2>> one(n+1);
for(int i=0;i<=n;i++) one[i]={t[i],i};
vector<array<int,2>> two(n+1);
for(int i=0;i<=n;i++) two[i]={s[i],i};
sort(one.begin(),one.end());
sort(two.begin(),two.end());
vector<int> h(n+1,0);
for(int i=0;i<=n;i++) h[one[i][1]]=i;
for(int i=0;i<=n;i++)
{
one[i][1]=i;
two[i][1]=h[two[i][1]];
//~ cout << "[" << one[i][0] << "," << one[i][1] << "] [" << two[i][0] << "," << two[i][1] << "]" << endl;
}
vector<int> p(n+1,0);
for(int i=0;i<=n;i++) p[i]=i;
vector<int> sz(n+1,1);
function<int(int)> find_set=[&](int a)->int
{
if(a==p[a]) return a;
else return p[a]=find_set(p[a]);
};
int cycles=n+1;
auto merge_sets=[&](int a,int b)
{
a=find_set(a);
b=find_set(b);
if(a==b) return;
cycles--;
if(sz[a]<sz[b]) swap(a,b);
p[b]=a;
sz[a]+=sz[b];
};
auto cost=[&](int a,int b)->int{return max(0,one[a][0]-two[b][0]);};
vector<int> to(n+1,0);
ll res=0;
for(int i=0;i<=n;i++)
{
merge_sets(i,two[i][1]);
res+=cost(i,i);
to[i]=i;
}
priority_queue<array<int,2>,vector<array<int,2>>,greater<array<int,2>>> q;
auto eval=[&](int i)->int
{
return (cost(i,to[i+1])+cost(i+1,to[i])-cost(i,to[i])-cost(i+1,to[i+1]));
};
for(int i=0;i<n;i++) q.push({eval(i),i});
while(!q.empty())
{
auto [tmp,i]=q.top();
q.pop();
//~ cout << "[i=" << i << "], sets: " << find_set(i) << " " << find_set(i+1) << endl;
if(eval(i)!=tmp) continue;
if(find_set(i)==find_set(i+1)) continue;
//~ cout << "process [" << i << ",eval=" << tmp << "]" << endl;
res+=eval(i);
merge_sets(i,i+1);
swap(to[i],to[i+1]);
if(i-1>=0) q.push({eval(i-1),i-1});
if(i+2<=n) q.push({eval(i+1),i+1});
}
assert(cycles==1);
return res;
}
# | 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... |