Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Creating a segment tree in C++ and update a particular value

//segment tree making and update a particular value
#include<iostream>
#include<vector>
#include<algorithm>
#include<math.h>
#include<cstring>
using namespace std;

void makest(int arr[],int st[], int ss, int se, int si)
{
    if( ss==se)
    {
        st[si]=arr[se];
        return ;
    }
    int mid=(se+ss)/2;
    makest(arr, st, ss, mid, 2*si+1);
    makest( arr, st, mid+1, se, 2*si+2);
    st[si]=st[2*si+1]+ st[2*si+2];
}
void updatest(int st[], int ss, int se, int si,int index,int diff)
{
    if( index <ss || index >se)
    {
        return;
    }
        st[si]=st[si]+diff;
        if( se!=ss)
        {
        int mid=(ss+se)/2;
        updatest(st, ss, mid, 2*si+1, index,diff);
        updatest(st, mid+1,se,  2*si+2, index ,diff);
        }
}
int main()
{
    int arr[]={1,2,3,4,5,6};
    int height=(int)(ceil(log2(6)));
    int size=(int)2*((int)pow( 2, height)-1);
    int st[size];
    memset( st, 0, sizeof(st));
    makest(arr, st, 0, 5, 0);
    for ( int i=0;i< size;i ++)
    {
        cout<< st[i]<<endl;
    }
    int index=3;
    int diff=2;
    updatest( st, 0, size, 0, index, diff);
    cout<< "after upadation in my segment tree";
    for ( int i=0;i< size;i ++)
    {
        cout<< st[i]<<endl;
    }
    return 0;
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.