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;
#define pb push_back
#define fi first
#define se second
#define all(x) x.begin(), x.end()
#define allr(x) x.rbegin(), x.rend()
#define mp make_pair
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
const int MAXN = 2e5+10;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const int MOD = 1e9+7;
void dfs(int ver, int val, vector<vector<int>>& adj, vector<int>& cmp){
cmp[ver]=val;
for(auto u : adj[ver])
if(!cmp[u]) dfs(u, val, adj, cmp);
}
int pai[MAXN], peso[MAXN];
int find(int x){ return (pai[x]==x ? x : pai[x]=find(pai[x])); }
void join(int a, int b){
a=find(a); b=find(b);
if(a==b) return;
if(peso[a]>peso[b]) swap(a, b);
pai[a]=b;
peso[b]=max(peso[b], peso[a]+1);
}
long long plan_roller_coaster(vector<int> s, vector<int> t) {
vector<int> arr;
for(auto u : s) arr.pb(u);
for(auto u : t) arr.pb(u);
sort(all(arr));
arr.erase(unique(all(arr)), arr.end());
int n=(int)arr.size();
map<int, int> mp;
vector<int> g(n, 0);
for(int i=0;i<n;i++) mp[arr[i]]=i;
vector<vector<int>> adj(n);
adj[n-1].pb(0);
g[n-1]++; g[0]--;
for(int i=0;i<(int)s.size();i++){
g[mp[s[i]]]++; g[mp[t[i]]]--;
adj[mp[s[i]]].pb(mp[t[i]]);
}
ll ans=0ll;
for(int i=0;i<n-1;i++){
if(g[i]>0) adj[i+1].pb(i), ans+=(ll)g[i]*(ll)(arr[i+1]-arr[i]), g[i+1]+=g[i], g[i]=0;
else if(g[i]<0) adj[i].pb(i+1), g[i+1]+=g[i], g[i]=0;
}
int cnt=0;
vector<int> cmp(n, 0);
for(int i=0;i<n;i++)
if(!cmp[i]) dfs(i, ++cnt, adj, cmp);
for(int i=1;i<=cnt;i++) pai[i]=i;
vector<pair<int, pii>> edge;
for(int i=0;i<n-1;i++)
if(cmp[i]!=cmp[i+1]) edge.pb({arr[i+1]-arr[i], {cmp[i], cmp[i+1]}});
sort(all(edge));
for(auto u : edge){
if(find(u.se.fi)!=find(u.se.se)){
join(u.se.fi, u.se.se);
ans+=u.fi;
}
}
return ans;
}
# | 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... |