zoukankan      html  css  js  c++  java
  • A Simple Problem with Integers(线段树)

    http://poj.org/problem?id=3468

    题意:就是区间的查询与更新。。

    #include <stdio.h>
    #include <string.h>
    const int maxn=100010;
    const int maxm=6600000;
    #define LL long long
    struct node
    {
        int a,b;
        int l,r;
        LL  sum;
        LL  h;
    } A[maxm];
    int Num[maxn],cnt;
    void build(int root)
    {
        int a = A[root].a;
        int b = A[root].b;
        int mid = (a+b)>>1;
        A[root].h = 0;
        if (a==b)
        {
            A[root].sum = Num[a];
            return ;
        }
        int l = ++cnt;
        int r = ++cnt;
        A[l].a = a;
        A[l].b = mid;
        A[r].a = mid+1;
        A[r].b = b;
        build(l);
        build(r);
        A[root].sum = A[l].sum+A[r].sum;
        A[root].l = l;
        A[root].r = r;
    }
    LL Query(int t,int a1,int b1,LL h)
    {
        int a = A[t].a;
        int b = A[t].b;
        int mid = (a+b)>>1;
        if (a==a1&&b==b1)
            return A[t].sum+(b1-a1+1)*h;
        if (b1 <= mid)
            return Query(A[t].l,a1,b1,A[t].h+h);
        if (a1 > mid)
            return Query(A[t].r,a1,b1,A[t].h+h);
        LL suml = Query(A[t].l,a1,mid,A[t].h+h);
        LL sumr = Query(A[t].r,mid+1,b1,A[t].h+h);
        return suml+sumr;
    }
    void Update(int t,int a1,int b1,int c)
    {
        int a = A[t].a;
        int b = A[t].b;
        int l = A[t].l;
        int r = A[t].r;
        int mid = (a+b)>>1;
        A[t].sum += (b1-a1+1)*c;
        if (a==a1&&b==b1)
        {
            A[t].h+=c;
            return ;
        }
        if (b1 <= mid)
            Update(l,a1,b1,c);
        else if (a1 > mid)
            Update(r,a1,b1,c);
        else
        {
            Update(l,a1,mid,c);
            Update(r,mid+1,b1,c);
        }
    }
    int main()
    {
        int N,Q,a,b,c;
        char s[3];
        cnt = 0;
        scanf("%d%d",&N,&Q);
        for (int i = 1; i <= N; i++)
            scanf("%d",&Num[i]);
        getchar();
        int t = ++cnt;
        A[t].a = 1;
        A[t].b = N;
        build(t);
        while(Q--)
        {
            scanf("%s",s);
            if (s[0]=='Q')
            {
                scanf("%d%d",&a,&b);
                printf("%lld
    ",Query(1,a,b,0));
            }
            else
            {
                scanf("%d%d%d",&a,&b,&c);
                Update(1,a,b,c);
            }
        }
        return 0;
    }
    View Code
  • 相关阅读:
    (转)MySQL中MyISAM引擎与InnoDB引擎性能简单测试
    (转)数据库水平切分的实现原理解析
    ECShop笔记(品牌类)
    ECShop笔记(通用类)
    (转)InnoDB的性能(zz)
    ECSHOP笔记(商品类 三)
    ECShop笔记(积分类)
    ECShop笔记(商品类)
    ECShop笔记(二)
    phpcms 点击排行榜的改进
  • 原文地址:https://www.cnblogs.com/lahblogs/p/3543448.html
Copyright © 2011-2022 走看看