当前位置 : 主页 > 手机开发 > harmonyos >

线段树模板

来源:互联网 收集:自由互联 发布时间:2023-08-25
#includestdio.h #includeiostream int max(int x,int y) { return xy?x:y; } int a[300000]; struct ele { int Left; int Right; int Max; int Sum; }p[700000]; void Build(int L,int R,int Step) { p[Step].Left=L; p[Step].Right=R; if(L==R) p[Step].Sum
#include<stdio.h> 

 #include<iostream> 

 int max(int x,int y) 

 { 

   return x>y?x:y; 

 } 

 int a[300000]; 

 struct ele 

 { 

     int Left; 

     int Right; 

     int Max; 

     int Sum; 

 }p[700000]; 

 void Build(int L,int R,int Step) 

 { 

     p[Step].Left=L; 

     p[Step].Right=R; 

     if(L==R) 

         p[Step].Sum=p[Step].Max=a[L]; 

     else 

     { 

         int Mid=(L+R)/2; 

         Build(L,Mid,2*Step); 

         Build(Mid+1,R,2*Step+1); 

         p[Step].Max=max(p[Step*2].Max,p[Step*2+1].Max); 

         p[Step].Sum=p[Step*2].Sum+p[Step*2+1].Sum; 

     } 

 } 

 void Update(int x,int y,int Step) 

 { 

     if(p[Step].Left==x&&p[Step].Right==x) 

         p[Step].Max=p[Step].Sum=y; 

      else 

     { 

         int Mid=(p[Step].Left+p[Step].Right)/2; 

         if(x<=Mid) 

             Update(x,y,2*Step); 

         else 

             Update(x,y,2*Step+1); 

         p[Step].Max=max(p[Step*2].Max,p[Step*2+1].Max); 

         p[Step].Sum=p[Step*2].Sum+p[Step*2+1].Sum; 

     } 

 } 

 int Max(int x,int y,int Step) 

 { 

     if(p[Step].Left==x&&p[Step].Right==y) 

         return p[Step].Max; 

     else 

     { 

         int Mid=(p[Step].Left+p[Step].Right)/2; 

         if(y<=Mid) 

             return Max(x,y,2*Step); 

         else 

         if(x>=Mid+1) 

             return Max(x,y,2*Step+1); 

         else 

             return max(Max(x,Mid,2*Step),Max(Mid+1,y,2*Step+1)); 

     } 

 } 

 int Sum(int x,int y,int Step) 

 { 

     if(p[Step].Left==x&&p[Step].Right==y) 

         return p[Step].Sum; 

     else 

     { 

         int Mid=(p[Step].Left+p[Step].Right)/2; 

         if(y<=Mid) 

             return Sum(x,y,2*Step); 

         else 

         if(x>=Mid+1) 

             return Sum(x,y,2*Step+1); 

         else 

             return Sum(x,Mid,2*Step)+Sum(Mid+1,y,2*Step+1); 

     } 

 } 

 int main() 

 { 

     int n,m; 

     int i,j,k; 

     while(scanf("%d%d",&n,&m)!=EOF) 

     { 

         for(i=1;i<=n;i++) 

             scanf("%d",&a[i]); 

         Build(1,n,1); 

         while(m--) 

         { 

             scanf("%d%d%d",&i,&j,&k); 

             if(i==1) 

                 Update(j,k,1); 

             if(i==2) 

                 printf("%d\n",Sum(j,k,1)); 

             if(i==3) 

                 printf("%d\n",Max(j,k,1)); 

         } 

     } 

     return 0; 

 }
上一篇:dij 邻接表
下一篇:没有了
网友评论