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 "railroad.h"
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
///Disjoint Sets
///Sweep Line
///Set the balance always to 0, connecting special sections
int link[200005];
int setSize[200005];
int Find(int u)
{
if(link[u]==u) return u;
else return link[u]=Find(link[u]);
}
bool same(int u,int v)
{
return Find(u)==Find(v);
}
void unite(int u,int v)
{
u=Find(u);
v=Find(v);
if(u==v) return;
if(setSize[v]>setSize[u]) swap(u,v);
setSize[u]+=setSize[v];
link[v]=u;
}
void initDSU(int n)
{
for(int i=1;i<=n;i++){
setSize[i]=1;
link[i]=i;
}
}
struct event
{
int T;
int op;
int id; //Which special section
bool operator<(const event& a)
{
if(T<a.T) return true;
else{
if(T==a.T){
if(op<a.op) return true;
else return false;
}
else return false;
}
}
};
struct segment
{
ll length;
int a,b; //ID where it starts and ends
bool operator<(const segment& s)
{
return length<s.length;
}
};
vector<event> timeline;
vector<segment> remaining; //Not taken because its balance was 0
long long plan_roller_coaster(vector<int> s, vector<int> t) {
int n=s.size();
ll cost=0;
initDSU(n);
for(int i=0;i<n;i++){
event e={s[i],+1,i+1};
timeline.push_back(e);
e={t[i],-1,i+1};
timeline.push_back(e);
}
sort(timeline.begin(),timeline.end());
//Lines to the right are +1
//Lines to the left are -1
ll balance=-1; //Because there is a line that goes from inf to 1
for(int i=0;i<2*n-1;i++){
balance+=timeline[i].op;
if(balance<0){
unite(timeline[i].id,timeline[i+1].id); //Add a track from left to right (free) and connect i with i+1
}
else if(balance>0){
cost+=(ll)(timeline[i+1].T-timeline[i].T)*balance; //We need to slow down the train so we add "balance" tracks
//With length: distance between that two events
unite(timeline[i].id,timeline[i+1].id);
}
else if(balance==0){
segment s;
s.length=(timeline[i+1].T-timeline[i].T);
s.a=timeline[i].id;
s.b=timeline[i+1].id;
remaining.push_back(s);
}
}
sort(remaining.begin(),remaining.end());
set<int> R; //Roots
for(int i=1;i<=n;i++){
R.insert(Find(i));
}
int roots=R.size();
int i=0;
while(roots>1){ //Not fully connected
int a=remaining[i].a;
int b=remaining[i].b;
if(!same(a,b)){
unite(a,b);
cost+=remaining[i].length;
roots--;
}
i++;
}
return cost;
}
# | 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... |