CodeForces 1053C Putting Boxes Together
阿新 • • 發佈:2018-12-13
Codeforces Round #512 (Div. 1, based on Technocup 2019 Elimination Round 1) n=2e5個物品從左到右排列,第i個物品的位置pos[i],重量w[i]。每次詢問如果將pos[l]…pos[r]這段物品移到某個連續區間[x, x+(r-l)],且物品不能重疊,物品移動d米需要d*w[i]的費用,問最少需要多少費用。並且有修改物品重量的操作。 如果將每個物品pos[i]-=i,問題轉化為把物品移動到同一個點,變成了帶權中位數問題,由於pos是有序的,二分找到點,,維護。
#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; }