官方的题解:
因为我们要让货物移动总距离尽可能小,所以最后所使用的集装箱的初始位置在数轴上一定是一段区间。 如果固定了这个区间,那么最优方案就是把这些集装箱移动到这些集装箱的坐标中位数的位置。 答案满足可二分性,先二分答案。然后我们按照从左至右的顺序枚举区间的左端点,那么区间的右端点和 区间的中位数都是单调递增的,一遍枚举一遍维护即可。 复杂度O(n*log(sum(a[i])))
一些细节:
预处理出前缀数量的和以及前缀距离的和。再预处理出后缀数量的和以及后缀数量的和,通过公式计算判断是否符合条件。
#include"bits/stdc++.h"
#define fi first
#define se second
using namespace std;
typedef long long LL;
const int MX = 5e5+7;
const int N = 55;
const LL INF = 1e18;
const int inf = 1e8;
int n,a[MX];
LL T,prex[MX],pren[MX],sufx[MX],sufn[MX];
struct node{
int x,num;
}p[MX];
bool cmp(node a, node b)
{
return a.x < b.x;
}
inline LL get_prex(int l, int x)
{
return prex[x] - prex[l] - pren[l]*(p[x].x - p[l].x);
}
inline LL get_sufx(int x, int r)
{
return sufx[x] - sufx[r] - sufn[r]*(p[r].x-p[x].x);
}
bool check(LL num)
{
LL num2 = num/2+1;
int lp = 0, mp = 1, rp = 1;
int flag = 0;
while(1){
while(rp <= n && pren[rp] - pren[lp] < num) rp++;
while(mp <= n && pren[mp] - pren[lp] < num2) mp++;
if(rp > n || mp > n) break;
if(get_prex(lp,mp)+get_sufx(mp,rp)+(num-(pren[rp-1]-pren[lp]))*(p[rp].x-p[mp].x) <= T) return 1;
lp++;
}
rp = n, mp = n, lp = n-1;
while(1){
while(lp >= 0 && pren[rp] - pren[lp] < num) lp--;
while(mp >= 1 && pren[mp] - pren[lp] < num2) mp--;
if(lp < 0 || mp < 1) break;
if(get_prex(lp+1,mp)+get_sufx(mp,rp+1)+(num-(pren[rp]-pren[lp+1]))*(p[mp].x-p[lp+1].x) <= T) return 1;
rp--;
}
return 0;
}
int main()
{
#ifdef LOCAL
freopen("input.txt","r",stdin);
#endif // LOCAL
while(~scanf("%d%lld",&n,&T)){
T >>= 1;
LL l = 1, r = 0;
for(int i = 1; i <= n; i++)
scanf("%d",&p[i].x);
for(int i = 1; i <= n; i++)
scanf("%d",&p[i].num);
sort(p+1,p+1+n,cmp);
p[0].x = p[1].x;
p[n+1].x = p[n].x;
pren[0] = prex[1] = 0;
for(int i = 1; i <= n; i++){
r += p[i].num;
pren[i] = pren[i-1] + p[i].num;
prex[i] = pren[i-1]*(p[i].x-p[i-1].x) + prex[i-1];
}
sufn[n+1] = sufx[n+1] = 0;
for(int i = n; i >= 1; i--){
sufn[i] = sufn[i+1] + p[i].num;
sufx[i] = sufn[i+1]*(p[i+1].x-p[i].x) + sufx[i+1];
}
while(l <= r){
LL mid = l+r>>1;
if(check(mid)) l = mid + 1;
else r = mid - 1;
}
cout<<r<<endl;
}
return 0;
}