zoukankan      html  css  js  c++  java
  • 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;    
    }
  • 相关阅读:
    计算机的组成部分
    从LINQ开始之LINQ to Objects(下)
    从LINQ开始之LINQ to Objects(上)
    vue.js devtools-------调试vue.js的开发者插件
    Sublime快捷键(一)
    配置node,sass,淘宝镜像环境
    vue--------脚手架vue-cli搭建
    Sublime之插件的安装(一)
    计算机网络之万维网WWW
    官网下载java相关资源
  • 原文地址:https://www.cnblogs.com/lwer/p/2712991.html
Copyright © 2011-2022 走看看