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 <vector>
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define vll vector<ll>
const ll inf=1e16;
ll small_part(vll&r,vll&b) // O(n+m) -> 14
{
ll n=r.size();
ll m=b.size();
ll sm=0;
int i=n-1;
int j=0;
while(0<=i and j<m)
{
ll mp=b[j]-r[i];
ll oth=b[j]-r[n-1] + b[0]-r[i];
sm+=min(mp,oth);
j++;
i--;
}
while(0<=i)
{
sm+=(b[0]-r[i]);
i--;
}
while(j<m)
{
sm+=(b[j]-r[n-1]);
j++;
}
return sm;
}
ll solve_mega(vll&r,vll&b)
{
vector<pair<ll,ll>> tp;
for(auto&i:r)tp.push_back({i,0});
for(auto&i:b)tp.push_back({i,1});
sort(begin(tp),end(tp));
ll n=tp.size();
ll dp[n+1]={0};
dp[0]=0;
for(int i=1;i<=n;i++)
dp[i]=1e15;
for(int i=1;i<=n;i++)
{
// cout<<"Computing dp for "<<i<<endl;
int j=i-1;
ll sm=0;
ll len=0;
ll last=0;
vll fp;
while(j>=0 and tp[j].second==tp[i-1].second)
{
len++;
sm+=tp[j].first;
fp.push_back(tp[j].first);
j--;
}
// cout<<"Reach "<<j<<' '<<sm<<' '<<last<<endl;
int l=j;
ll sm1=0,len1=0;
vll sp;
while(j>=0 and tp[j].second==tp[l].second)
{
sm1+=tp[j].first;
len1++;
sp.push_back(tp[j].first);
ll cur=dp[j] + small_part(sp,fp);
dp[i]=min(dp[i],cur);
j--;
}
}
return dp[n];
}
long long min_total_length(std::vector<int> RR, std::vector<int> BB)
{
vector<ll> r,b;
for(auto i:RR)r.push_back(i);
for(auto i:BB)b.push_back(i);
ll n=r.size();
ll m=b.size();
if(r.back()<b[0])
{
return small_part(r,b);
}
else if((n*m)<=1e6)
{
map<pair<ll,ll>,ll> dp;
dp[{0,0}]=0;
priority_queue<pair<ll,pair<int,int>>,vector<pair<ll,pair<int,int>>>,greater<pair<ll,pair<int,int>>>>pq;
pq.push({0,{0,0}});
while(pq.size()>0)
{
auto it=pq.top();
pq.pop();
int i=it.second.first;
int j=it.second.second;
if(i==n and j==m)break;
if(i==n or j==m)continue;
// cout<<"At "<<i<<' '<<j<<' '<<dp[i][j]<<endl;
ll nc=dp[{i,j}]+abs(r[i]-b[j]);
if(dp.find({i+1,j+1})==dp.end() or nc<dp[{i+1,j+1}])
{
dp[{i+1,j+1}]=nc;
pq.push({nc,{i+1,j+1}});
}
if(dp.find({i+1,j})==dp.end() or nc<dp[{i+1,j}])
{
dp[{i+1,j}]=nc;
pq.push({nc,{i+1,j}});
}
if(dp.find({i,j+1})==dp.end() or nc<dp[{i,j+1}])
{
dp[{i,j+1}]=nc;
pq.push({nc,{i,j+1}});
}
}
return dp[{n,m}];
}
else{
return solve_mega(r,b);
}
}
Compilation message (stderr)
wiring.cpp: In function 'long long int solve_mega(std::vector<long long int>&, std::vector<long long int>&)':
wiring.cpp:51:12: warning: unused variable 'last' [-Wunused-variable]
51 | ll last=0;
| ^~~~
# | 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... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |