# | Time | Username | Problem | Language | Result | Execution time | Memory |
---|---|---|---|---|---|---|---|
332130 | LifeHappen__ | Roller Coaster Railroad (IOI16_railroad) | C++14 | 0 ms | 0 KiB |
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"
#define forinc(i,a,b) for(int i=a;i<=b;++i)
#define fordec(i,a,b) for(int i=a;i>=b;--i)
#define all(a) a.begin(),a.end()
using namespace std;
const int N = 2e5+5;
int n, s[N], t[N];
int that[N], in[N], out[N], res;
struct DSU
{
int n;
vector<int> id;
DSU(int n) : n(n), id(n+1,-1) {}
int root(int u)
{
return id[u]<0 ? u : id[u]=root(id[u]);
}
bool join(int u,int v)
{
if((u=root(u))==(v=root(v)))
return 0;
if(id[u]>id[v])
swap(u,v);
id[u] += id[v];
id[v] = u;
return 1;
}
};
struct edge
{
int u, v, c;
};
vector<edge> E;
long long plan_roller_coaster(int n, int[] s, int[] t)
{
vector<int> rrh;
forinc(i,1,n)
{
rrh.push_back(s[i]);
rrh.push_back(t[i]);
}
sort(all(rrh));
rrh.erase(unique(all(rrh)),rrh.end());
int ma = rrh.size();
DSU dsu(ma);
forinc(i,1,n)
{
int _s = lower_bound(all(rrh),s[i]) - rrh.begin() + 1;
int _t = lower_bound(all(rrh),t[i]) - rrh.begin() + 1;
that[_s] = s[i], that[_t] = t[i];
out[_s]++;
in[_t]++;
dsu.join(_s,_t);
}
out[ma]++;
in[1]++;
fordec(i,ma,1)
{
if(in[i] > out[i])
{
in[i-1] += in[i]-out[i];
res += (in[i]-out[i])*(that[i]-that[i-1]);
dsu.join(i-1,i);
}
else if(in[i] < out[i])
{
out[i-1] += out[i] - in[i];
dsu.join(i-1,i);
}
}
forinc(i,1,ma-1) if(dsu.root(i) != dsu.root(i+1))
E.push_back({i,i+1,that[i+1]-that[i]});
sort(all(E),[](const edge &a, const edge &b)
{
return a.c < b.c;
});
for(edge e:E)
{
if(dsu.join(e.u, e.v))
res += e.c;
}
return res;
}