POJ3468 A Simple Problem with Integers【线段树 成段更新+求和 lazy标志】

简介:

 用longlong替换__int64也成。

#define LL long long

输入输出用%lld

Problem: 3468   User: qq1203456195
Memory:4284K   Time: 1579MS
Language: C   Result: Accepted

 

复制代码
#include <stdio.h>
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define maxn 111111
#define INT __int64
INT sum[maxn<<2],lazy[maxn<<2];
INT ret;
void PullUp(int rt)
{
    sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void PushDown(int rt,int len)
{
    lazy[rt<<1]+=lazy[rt];
    lazy[rt<<1|1]+=lazy[rt];
    sum[rt<<1]+=lazy[rt]*(len-(len>>1));
    sum[rt<<1|1]+=lazy[rt]*(len>>1);
    lazy[rt]=0;
}
void build(int l,int r,int rt)
{
    int m=(r+l)>>1;
    lazy[rt]=0;
    if(l==r){
        scanf("%I64d",&sum[rt]);
        return;
    }
    build(lson);
    build(rson);
    PullUp(rt);
}
void update(INT v,int L,int R,int l,int r,int rt)
{
    int m=(l+r)>>1;
    if(l>=L&&r<=R)
    {
        sum[rt]+=(r-l+1)*v;
        lazy[rt]+=v;
        return;
    }
    if(lazy[rt]!=0)    PushDown(rt,r-l+1);
    if(L<=m)        update(v,L,R,lson);
    if(R>m)            update(v,L,R,rson);
    PullUp(rt);
}
void query(int L,int R,int l,int r,int rt)
{
    int m=(l+r)>>1;
    if(l>=L&&r<=R)
    {
        ret+=sum[rt];
        return;
    }
    if(lazy[rt]!=0)    PushDown(rt,r-l+1);
    if(L<=m)        query(L,R,lson);
    if(R>m)            query(L,R,rson);    
}
int main()
{
    int n,q,L,R;
    INT v;
    char op[2];
    while (~scanf("%d%d",&n,&q))
    {
        build(1,n,1);
        while (q--){
            scanf("%s",op);
            if(op[0]=='C'){
                scanf("%d%d%I64d",&L,&R,&v);
                update(v,L,R,1,n,1);
            }
            if(op[0]=='Q'){
                ret=0;
                scanf("%d%d",&L,&R);
                query(L,R,1,n,1);
                printf("%I64d\n",ret);
            }
        }
    }
    return 0;
}
复制代码

 

 

本文转自ZH奶酪博客园博客,原文链接:http://www.cnblogs.com/CheeseZH/archive/2012/05/03/2480564.html,如需转载请自行联系原作者


相关文章
|
开发框架 .NET
poj 3468 A Simple Problem with Integers线段树区间修改
题目意思很简单,有N个数,Q个操作, Q l r 表示查询从l到r 的和,C l r v 表示将从l到r 的值加上v,明显的线段树,不知道线段树的人肯定暴力,肯定超时,哈哈!!
33 0
|
算法
Light oj 1082 - Array Queries(区间最小值)
这里只要知道这种算法即可,因为数据量过大,都编译不通过,不过思想算法没有任何问题。
30 0
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
Optimal Coin Change(完全背包计数)
题目描述 In a 10-dollar shop, everything is worthy 10 dollars or less. In order to serve customers more effectively at the cashier, change needs to be provided in the minimum number of coins. In this problem, you are going to provide a given value of the change in different coins.
92 0
|
Java
HDOJ/HDU 1297 Children’s Queue(推导~大数)
HDOJ/HDU 1297 Children’s Queue(推导~大数)
139 0