S
o
u
r
c
e
:
Source:
Source:Codeforces Round #512 (Div. 1, based on Technocup 2019 Elimination Round 1)
P
r
o
b
e
l
m
:
Probelm:
Probelm:n=2e5个物品从左到右排列,第i个物品的位置pos[i],重量w[i]。每次询问如果将pos[l]…pos[r]这段物品移到某个连续区间[x, x+(r-l)],且物品不能重叠,物品移动d米需要d*w[i]的费用,问最少需要多少费用。并且有修改物品重量的操作。
I
d
e
a
:
Idea:
Idea:如果将每个物品pos[i]-=i,问题转化为把物品移动到同一个点,变成了带权中位数问题,由于pos是有序的,二分
s
u
m
L
<
s
u
m
R
sumL<sumR
sumL<sumR找到
M
M
M点,
A
n
s
=
w
[
i
]
∗
a
b
s
(
p
o
s
[
M
]
−
p
o
s
[
i
]
)
Ans = w[i]*abs(pos[M]-pos[i])
Ans=w[i]∗abs(pos[M]−pos[i]),维护
w
[
i
]
和
w
[
i
]
∗
p
o
s
[
i
]
w[i]和w[i]*pos[i]
w[i]和w[i]∗pos[i]。
C
o
d
e
:
Code:
Code:
#include<bits/stdc++.h>
using namespace std;
#define I inline
typedef long long LL;
const int N = 2e5+10;
const int MOD = 1e9+7;
I void add(LL &a, const LL &b) { if((a+=b) >= MOD) a -= MOD; }
int a[N], w[N];
LL c1[N], c2[N];
I LL sum1(int x) { LL ret=0; while(x) ret+=c1[x], x-=(x&-x); return ret; }
I void add1(int x, LL d) { while(x<N) c1[x]+=d, x+=(x&-x); }
I LL sum2(int x) { LL ret=0; while(x) add(ret, c2[x]), x-=(x&-x); return ret; }
I void add2(int x, LL d) { while(x<N) add(c2[x], d), x+=(x&-x); }
I void work() {
int n, q;
scanf("%d%d", &n, &q);
for(int i = 1; i <= n; i++) {
scanf("%d", a+i);
a[i] -= i;
}
for(int i = 1; i <= n; i++) {
scanf("%d", w+i);
add1(i, w[i]);
add2(i, 1LL*w[i]*a[i]%MOD);
}
while(q--) {
int x, y;
scanf("%d%d", &x, &y);
if(x < 0) {
add1(-x, -w[-x]+y);
add2(-x, (1LL*(-w[-x]+y)*a[-x]%MOD+MOD)%MOD);
w[-x] = y;
}
else {
int L = x, R = y;
LL t = sum1(L-1), sum = sum1(R)-t;
while(L < R) {
int M = (L+R)>>1;
if(2*(sum1(M)-t) < sum) L = M+1;
else R = M;
}
LL t1 = ((sum1(L)-t)%MOD*a[L]%MOD-(sum2(L)-sum2(x-1))%MOD)%MOD;
LL t2 = (-(sum1(y)-sum1(L))%MOD*a[L]%MOD+(sum2(y)-sum2(L))%MOD)%MOD;
LL ans = (t1+t2)%MOD;
printf("%lld\n", (ans+MOD)%MOD);
}
}
}
int main() {
work();
return 0;
}