hdu 1166

 单点更新的线段树,搞了我好久啊。。。。在细节上,该不该加一,什么的处理了很久,而且还不会用数组来写线段树,只能用结构体。。。接下来就要做区间更新了,先留个单点更新。。。

View Code
  1 #include<iostream>
  2 #include<cstdio>
  3 #include<cmath>
  4 #include<cstring>
  5 #include<stdlib.h>
  6 #define max(a,b) a>b?a:b
  7 struct p
  8 {
  9     int u,v,t;
 10     struct p*lc,*rc;
 11 }*head;
 12 int n,i;
 13 int add(int x,int y,struct p*q)
 14 {
 15     if(q->u==q->v&&q->u==x)
 16     {
 17         q->t+=y;
 18         return 0;
 19     }
 20     int mid=(q->u+q->v)/2;
 21     if(x<=mid)
 22     {
 23         q->t+=y;
 24         add(x,y,q->lc);
 25     }
 26     else
 27     {
 28         q->t+=y;
 29         add(x,y,q->rc);
 30     }
 31     return 0;
 32 }
 33 int sub(int x,int y,struct p*q)
 34 {
 35     if(q->u==q->v&&q->u==x)
 36     {
 37         q->t-=y;
 38         return 0;
 39     }
 40     int mid=(q->u+q->v)/2;
 41     if(x<=mid)
 42     {
 43         q->t-=y;
 44         sub(x,y,q->lc);
 45     }
 46     else
 47     {
 48         q->t-=y;
 49         sub(x,y,q->rc);
 50     }
 51     return 0;
 52 }
 53 struct p* buildtree(int u,int v,struct p *q)
 54 {
 55     q->u=u;
 56     q->v=v;
 57     if(q->u==q->v)
 58     {
 59         scanf("%d",&q->t);
 60     }
 61     else
 62     {
 63     int mid=(u+v)/2;
 64     q->lc=(struct p*)malloc(sizeof(struct p));
 65     buildtree(u,mid,q->lc);
 66     q->rc=(struct p*)malloc(sizeof(struct p));
 67     buildtree(mid+1,v,q->rc);
 68     q->t=q->lc->t+q->rc->t;
 69     }
 70     return q;
 71 }
 72 int qur(int u,int v,struct p*q)
 73 {
 74     if(q->u==u&&q->v==v)
 75         return q->t;
 76     int mid=(q->u+q->v)/2;
 77     if(v<=mid)
 78         return qur(u,v,q->lc);
 79     if(u>mid)
 80         return qur(u,v,q->rc);
 81     return qur(u,mid,q->lc)+qur(mid+1,v,q->rc);
 82 }
 83 int main()
 84 { 
 85     int t,t1=0 ;
 86     scanf("%d",&t);
 87     while(++t1<=t)
 88     {
 89         char q[10];
 90         int x,y;
 91         printf("Case %d:\n",t1);
 92         scanf("%d",&n);
 93         head=(struct p*)malloc(sizeof(struct p));
 94         buildtree(1,n,head);
 95         getchar();
 96         while(1)
 97         {
 98             scanf("%s",q);    
 99             if(q[0]=='E')
100                break;
101            scanf("%d%d",&x,&y);
102            getchar();
103            if(q[0]=='A')
104                add(x,y,head);
105            else
106            if(q[0]=='S')
107                sub(x,y,head);
108            else
109            {
110                printf("%d\n",qur(x,y,head));
111            }
112         }
113     }
114     return 0;
115 }

 

posted on 2012-07-21 13:00  usp10  阅读(188)  评论(0编辑  收藏  举报

导航