题解:#2.A + B Problem 审核通过

Brilliance 紫罗兰 2024-03-21 18:43:32 46

线段树代码

#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<iostream>
using namespace std;
struct node{
   int val,l,r;
};
node t[5];
int a[5],f[5];
int n,m;
void init(){
   for(int i=1;i<=2;i++){
       scanf("%d",&a[i]);
   }
}
void build(int l,int r,int node){//这是棵树
   t[node].l=l;t[node].r=r;t[node].val=0;
   if(l==r){
       f[l]=node;
       t[node].val=a[l];
       return;
   }
   int mid=(l+r)>>1;
   build(l,mid,node*2);
   build(mid+1,r,node*2+1);
   t[node].val=t[node*2].val+t[node*2+1].val;
}
void update(int node){
   if(node==1)return;
   int fa=node>>1;
   t[fa].val=t[fa*2].val+t[fa*2+1].val;
   update(fa);
}
int find(int l,int r,int node){
   if(t[node].l==l&&t[node].r==r){
       return t[node].val;
   }
   int sum=0;
   int lc=node*2;int rc=lc+1;
   if(t[lc].r>=l){
       if(t[lc].r>=r){
           sum+=find(l,r,lc);
       }
       else{
           sum+=find(l,t[lc].r,lc);
       }
   }
   if(t[rc].l<=r){
       if(t[rc].l<=l){
           sum+=find(l,r,rc);
       }
       else{
           sum+=find(t[rc].l,r,rc);
       }
   }
   return sum;
}
int main(){
   init();
   build(1,2,1);
   printf("%d",find(1,2,1));
}
{{ vote && vote.total.up }}

共 1 条回复

CPP 刷题王

。。。