# Bzoj 2752 高速公路 (期望,线段树)

$1$$2$号点的边连得是. 编号为$1$的点.查询的时候把$r - 1$就好了.

$ans = \sum_{i=l}^ra[i]*(r-i+1)(i-l+1)$

$ans = (r - l + 1 - r * l) * sum1 + (r + l) * sum2 - sum3$

$sum1 = \sum_{i=l}^r a[i]$
$sum2 = \sum_{i=l}^r a[i]*i$
$sum3 = \sum_{i=l}^r a[i] * i * i$

$sum1 = lson_{sum1} + rson_{sum1}$
$sum2 = lson_{sum2} + rson_{sum2}$
$sum3 = lson_{sum3} + rson_{sum3}$

$sum1$比较简单,直接加上区间的长度乘以$k$即可.
$sum2$要加上$k*\sum i$然后维护一下区间$i$的和.我们称它为$sum5$,或者考虑等差数列求和的方法也可以.
$sum3$要加上$k * \sum i ^2$我们这里必须要维护$sum4$,它代表$\sum i^2$
$sum4$$sum5$ 是一个定值.在建树的时候更新就行了.

CODE:

#include <iostream>
#include <cstdio>
#define lson now << 1
#define rson now << 1 | 1
#define ll long long
const ll maxN = 100000 + 7;

ll x = 0,f = 1;char c = getchar();
while(c < '0' || c > '9') {if(c == '-')f = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x * 10 + c - '0';c = getchar();}
return x * f;
}

ll gcd(ll a,ll b) {
return !b ? a : gcd(b,a % b);
}

struct Node {
ll sum[6];
ll lazy;
ll l,r;
}tree[maxN << 2];
ll sum1,sum2,sum3;

void updata(ll now) {
tree[now].sum[1] = tree[lson].sum[1] + tree[rson].sum[1];
tree[now].sum[2] = tree[lson].sum[2] + tree[rson].sum[2];
tree[now].sum[3] = tree[lson].sum[3] + tree[rson].sum[3];
return ;
}

void build(ll l,ll r,ll now) {
tree[now].l = l;tree[now].r = r;
if(l == r) {
tree[now].sum[4] = l * l;
tree[now].sum[5] = l;
return ;
}
ll mid = (l + r) >> 1;
build(l,mid,lson);
build(mid + 1,r,rson);
tree[now].sum[4] = tree[lson].sum[4] + tree[rson].sum[4];
tree[now].sum[5] = tree[lson].sum[5] + tree[rson].sum[5];
return ;
}

void work(ll now,ll k) {
tree[now].sum[1] += (tree[now].r - tree[now].l + 1) * k;
tree[now].sum[2] += k * tree[now].sum[5];
tree[now].sum[3] += k * tree[now].sum[4];
tree[now].lazy += k;
}

void pushdown(ll now) {
work(lson,tree[now].lazy);
work(rson,tree[now].lazy);
tree[now].lazy = 0;
return ;
}

void modify(ll l,ll r,ll now,ll val) {
if(tree[now].l >= l && tree[now].r <= r) {
work(now,val);
return ;
}
if(tree[now].lazy) pushdown(now);
ll mid = (tree[now].l + tree[now].r) >> 1;
if(mid >= l) modify(l,r,lson,val);
if(mid < r) modify(l,r,rson,val);
updata(now);
return ;
}

void query(ll l,ll r,ll now) {
if(tree[now].l >= l && tree[now].r <= r)  {
sum1 += tree[now].sum[1];
sum2 += tree[now].sum[2];
sum3 += tree[now].sum[3];
return ;
}
if(tree[now].lazy) pushdown(now);
ll mid = (tree[now].l + tree[now].r) >> 1;
if(mid >= l) query(l,r,lson);
if(mid < r) query(l,r,rson);
return ;
}

int main()
{
ll n,m,l,r,v;
char s[3];
build(1,n,1);
while(m --) {
scanf("%s",&s);
if(s[0] == 'C') {
modify(l,r,1,v);
}
else {
ll a;
sum1 = sum2 = sum3 = 0;
query(l,r,1);
a = (r - l + 1 - r * l) * sum1 + (r + l) * sum2 - sum3;
ll b = ( r - l + 2 ) * (r - l + 1) / 2;
ll g = gcd(a,b);
printf("%lld/%lld\n", a / g,b / g);
}
}
return 0;
}
posted @ 2018-10-04 15:35  Rlif  阅读(175)  评论(0编辑  收藏  举报