数据结构--线段树--成段更新(poj 3468 裸题)

鉴于在网上找的代码和我心中的好代码相差较大,贴个自己写的,不好莫怪哈~~

题目链接:http://poj.org/problem?id=3468

代码实现:

  1 #include "stdio.h"  //线段树成段更新 poj 3468
  2 #include "string.h"
  3 #include "stdlib.h"
  4 #define N 100005
  5 
  6 typedef struct node {
  7     int x;
  8     int y;
  9     __int64 sum;
 10     __int64 add;
 11 }point;
 12 
 13 point a[3*N];
 14 
 15 void PushDown(int t);
 16 __int64 query(int t,int x,int y);
 17 void update(int t,int x,int y,int k);
 18 void CreatTree(int t,int x,int y);
 19 
 20 int main()
 21 {
 22     int Q,n;
 23     int x,y,z;
 24     char ch[2];
 25     while(scanf("%d%d",&n,&Q)!=-1)
 26     {
 27         CreatTree(1,1,n);
 28         while(Q--)
 29         {
 30             scanf("%s",ch);
 31             if(ch[0]=='Q')
 32             {
 33                 scanf("%d %d",&x,&y);
 34                 printf("%I64d\n",query(1,x,y));
 35             }
 36             else
 37             {
 38                 scanf("%d %d %d",&x,&y,&z);
 39                 update(1,x,y,z);
 40             }
 41 
 42         }
 43     
 44     }
 45     return 0;
 46 }
 47 
 48 void update(int t,int x,int y,int k)
 49 {
 50     if(a[t].x==x && a[t].y==y)
 51     {
 52         a[t].add+=(__int64)k;
 53         a[t].sum+=(__int64)k*(a[t].y-a[t].x+1);
 54         return ;
 55     }
 56     
 57     PushDown(t);
 58     
 59     int temp=2*t;
 60     int mid=(a[t].x + a[t].y)/2;
 61 
 62     if(y<=mid)
 63         update(temp,x,y,k);
 64     else if(x>mid)
 65         update(temp+1,x,y,k);
 66     else
 67     {
 68         update(temp,x,mid,k);
 69         update(temp+1,mid+1,y,k);
 70     }
 71     a[t].sum=a[temp].sum+a[temp+1].sum;
 72 }
 73 
 74 
 75 void PushDown(int t)  //主要是这儿延迟一步更新。
 76 {
 77     if(a[t].add)
 78     {
 79         int temp=2*t;
 80         a[temp].add  += a[t].add;
 81         a[temp+1].add+= a[t].add;
 82         
 83         a[temp].sum  += a[t].add*(a[temp].y - a[temp].x+1);
 84         a[temp+1].sum+= a[t].add*(a[temp+1].y - a[temp+1].x+1);
 85         a[t].add=0;
 86     }
 87 }
 88 
 89 
 90 __int64 query(int t,int x,int y)
 91 {
 92     if(a[t].x==x && a[t].y==y)
 93         return a[t].sum;
 94     
 95     int mid=(a[t].x + a[t].y)/2;
 96     int temp=2*t;
 97     PushDown(t);
 98     if(y<=mid)
 99         return query(temp,x,y);
100     else if(x>mid)
101         return query(temp+1,x,y);
102     else
103         return query(temp,x,mid) + query(temp+1,mid+1,y);
104 
105 }
106 
107 void CreatTree(int t,int x,int y)  //还是建树
108 {
109     a[t].x=x;
110     a[t].y=y;
111     a[t].add=a[t].sum=0;
112     if(a[t].x==a[t].y)
113     {
114         scanf("%I64d",&a[t].sum);
115         return ;
116     }
117     int mid=(a[t].x + a[t].y)/2;
118     int temp=2*t;
119     CreatTree(temp,x,mid);
120     CreatTree(temp+1,mid+1,y);
121     a[t].sum+=a[temp].sum + a[temp+1].sum;
122     return ;
123 }

 



posted @ 2013-08-06 08:57  ruo_yu  阅读(196)  评论(0编辑  收藏  举报