【模板】線段樹

#include<math.h>
#include<algorithm>
#include<iostream>
using namespace std;
struct node
{
    int left,right;
    int max;
    node()
    {
        max=0;
    }
}tree[1000000];
int a[200000],ans;
int Build(int left,int right,int i)
{
    tree[i].left=left;
    tree[i].right=right;
    if(left==right)
        return tree[i].max=a[left];
    int mid=(left+right)/2;
    int a=Build(left,mid,2*i);
    int b=Build(mid+1,right,2*i+1);
	tree[i].max=max(a,b);
}
void update(int a,int b,int i)
{
    if(tree[i].left==tree[i].right&&tree[i].left==a)
    {
        tree[i].max=b;
        return;
    }
    if(a<=(tree[i].left+tree[i].right)/2)
        update(a,b,2*i);
    else
        update(a,b,2*i+1);
    tree[i].max=max(tree[2*i].max,tree[2*i+1].max);
}
int Query(int left,int right,int i)
{
    if(tree[i].left==left&&tree[i].right==right)
		return tree[i].max;
    int mid=(tree[i].left+tree[i].right)/2;
    if(right<=mid) Query(left,right,2*i);
    else if(left>mid) Query(left,right,2*i+1);
    else
		return max(Query(left,mid,2*i),Query(mid+1,right,2*i+1));
}

發佈了55 篇原創文章 · 獲贊 45 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章