• hdu 1166 线段树 解法 484MS


    #include <iostream>
    #include <stdio.h>
    #include <cstdlib>
    #include <string.h>
    #define MAX 50001
    using namespace std;
    int data[MAX];
    int sum;
    struct NODE 
    {
       int lRange,rRange;
       int sum;
    }node[MAX<<4];
    
    void build(int root,int lRange,int rRange)
    {
       node[root].lRange = lRange;
       node[root].rRange = rRange;
       if(lRange == rRange) {
          node[root].sum = data[lRange];
          return;
       }
       int mid = (lRange + rRange)>>1;
       build(root<<1,lRange,mid);
       build(root<<1|1,mid+1,rRange);
       node[root].sum = node[root<<1].sum + node[root<<1|1].sum;
    }
    
    void update(int root, int target,int var)
    {
       while(node[root].lRange != node[root].rRange)
       {
           node[root].sum += var;
           int tmp = root<<1;
           if(target <= node[tmp].rRange)
               root = tmp;
           else{
               root = tmp+1;
           }      
       }
       node[root].sum += var;
    }
    
    
    void Query(int root,int begin,int end)
    {
         if(node[root].lRange == begin && node[root].rRange == end){
           sum += node[root].sum;                     
           return ;
         }
         if(end <= node[root<<1].rRange){
            Query(root<<1,begin,end);
         } else if(begin >= node[root<<1|1].lRange) {
            Query(root<<1|1,begin,end);
         }else {
            Query(root<<1,begin,node[root<<1].rRange);
            Query(root<<1|1,node[root<<1|1].lRange,end);
         }
    }
    
    int main()
    {
        int T,n;
        char str[10];
        bool flag;
        int index,index1,index2,var;
        scanf("%d",&T);
        for(int i=1;i<=T;i++)
        {
          flag = false;
          scanf("%d",&n);
          for(int j=1;j<=n;j++)
            scanf("%d",&data[j]);        
            
          build(1,1,n);
          cout<<"Case "<<i<<":"<<endl;
          while(true)
          {
            scanf("%s",str);  
            if(strcmp(str,"Query")==0){
                scanf("%d%d",&index1,&index2);
                sum = 0;
                Query(1,index1,index2);
                cout<<sum<<endl;
            } else if(strcmp(str,"Add")==0){
                scanf("%d%d",&index,&var);  
                update(1,index,var);
            } else if(strcmp(str,"Sub")==0){
                scanf("%d%d",&index,&var);  
                update(1,index,-var);
            } else{
                break;
            }
          }
        }
        //system("pause");
     return 0;    
    }
  • 相关阅读:
    HDU 1221 Rectangle and Circle 考虑很多情况,good题
    HDU 1223 打表 + 大数
    17984 FFF团的怒火
    17978 倒不了的塔 注意题目
    .. HDU
    17972 Golden gun的巧克力
    9718 整数因子分解(必做) 分治法
    51NOD 1201 整数划分
    Amazon Rekognition 人脸识别
    AWS Config
  • 原文地址:https://www.cnblogs.com/lwer/p/2712991.html
Copyright © 2020-2023  润新知