HDU 5239 Doom The 2015 ACM-ICPC China Shanghai Metropolitan Programming Contest

来源:互联网 发布:shadownsocks ubuntu 编辑:程序博客网 时间:2024/06/11 04:36

题意

给定一段序列,你有一个sum(初始值为0),只有一种操作(l,r),就是将序列中从l到r区间内的数字加到sum上,之后将每个数字平方,每次操作输出一次sum的值。

题解

本来还是一道比较简单的线段树,但是有两个坑点。
1.给出的mod值非常大为2^63-2^31。当你进行平方运算的时候一定会溢出,所以乘法运算得用快速加法解决(mod+mod < 2^64)
2.由于MOD很大,会发现对于一个区间,在询问最多30次之后,会变成一个固定不变的数值。(需要打个表尝试T_T。。。)也就是对于任何一个区间,我们更新了30次之后就不再更新了。(这个必须有!!!否则TLE妥妥的)
剩下的东西就非常好理解了,贴一下我的AC代码~

#include<iostream>#include<algorithm>#include<cstdio>#include<cmath>#define INF 9223372034707292160#define ll unsigned __int64using namespace std;ll n,m,b[1000005],sum;struct node{    ll l,r,sum,add;}a[1001000<<1];void pushup(ll root){    a[root].sum = (a[root<<1].sum + a[root<<1|1].sum)%INF;    a[root].add = min(a[root<<1].add,a[root<<1|1].add);}void build_tree(ll root,ll l,ll r){    a[root].l = l;    a[root].r = r;    if(l == r){        a[root].sum = b[l];        a[root].add = 0;        return ;    }    ll mid = (l + r) >> 1;    build_tree(root<<1,l,mid);    build_tree(root<<1|1,mid+1,r);    pushup(root);}ll fun(ll a,ll b){    ll sum = 0;    while(b){        if(b&1){            sum = (sum + a) % INF;        }        b /= 2;        a = (2*a) % INF;    }    return sum;}void update(ll root,ll x,ll y){    ll l = a[root].l;    ll r = a[root].r;    if(l == x && r == y && x == y){## 标题 ##        a[root].sum = fun(a[root].sum,a[root].sum);        a[root].add++;        return ;    }    ll mid = (l + r) >> 1;    if(x > mid) update(root<<1|1,x,y);    else if(y <= mid) update(root<<1,x,y);    else{        update(root<<1|1,mid+1,y);        update(root<<1,x,mid);    }    pushup(root);}ll query(ll root,ll x,ll y){    ll l = a[root].l;    ll r = a[root].r;    if(l == x && r == y){        return a[root].sum;    }    ll mid = (l + r) >> 1;    if(y <= mid) return (query(root << 1,x,y))%INF;    else if(x > mid) return (query(root << 1|1,x,y))%INF;    else{        return (query(root << 1,x,mid)+query(root<<1|1,mid+1,y))%INF;    }}int main(){    int i,j,T,xxx = 1;    ll x,y;    cin >> T;    while(T--){        scanf("%I64d%I64d",&n,&m);        for(i=1;i<=n;i++){            scanf("%I64d",&b[i]);        }        build_tree(1,1,n);        printf("Case #%d:\n",xxx++);        sum = 0;        for(i=0;i<m;i++){            scanf("%I64d%I64d",&x,&y);            sum = (sum+query(1,x,y))%INF;            printf("%I64d\n",sum);            update(1,x,y);        }    }    return 0;}
0 0