How to optimize this segment tree problem for memory

Revision en1, by redgulli, 2020-06-05 11:26:03

I have been trying out this problem on Hackerearth.

https://www.hackerearth.com/practice/data-structures/advanced-data-structures/fenwick-binary-indexed-trees/practice-problems/algorithm/help-ashu-1/

This is my code:

#include<bits/stdc++.h>
using namespace std;


int evencount[400004];
bool A[100001];
int num;
void build(int node,int start,int end)
{
    if(start==end)
    {
        evencount[node]=(A[start]%2==0);
        return;
    }
    int mid=start+(end-start)/2;
    build(2*node+1,start,mid);
    build(2*node+2,mid+1,end);
    int left=2*node+1;
    int right=2*node+2;
    evencount[node]=evencount[left]+evencount[right];
}

void update(int node,int start,int end,int idx,int val)
{
    if(start==end)
    {
        A[idx]=val%2;
        evencount[node]=(val%2==0);
        return;
    }
    int mid=start+(end-start)/2;
    if(idx <= mid)
    {
        update(2*node+1,start,mid,idx,val);
    }
    else{
        update(2*node+2,mid+1,end,idx,val);
    }
    int left=2*node+1;
    int right=2*node+2;
    evencount[node]=evencount[left]+evencount[right];
}

int query(int node,int start,int end,int left,int right)
{
    if(end < left || start > right)
    {
        return 0;
    }
    if(left<=start && end>=right)
    return evencount[node];

    int mid=start+(end-start)/2;
    int p1,p2;
    p1=query(2*node+1,start,mid,left,right);
    p2=query(2*node+2,mid+1,end,left,right);
    return p1+p2;
}


int main(){
    int N;
    cin>>N;
    for(int i=0;i<N;i++)
    {
        cin>>num;
        A[i]=num%2;
    }
    int Q;
    cin>>Q;
    for(int i=0;i<Q;i++)
    {
        int q,a,b;
        cin>>q>>a>>b;
        if(q==0)
            update(0,0,N,a-1,b);
        else
        {
            int t=query(0,0,N,a-1,b-1);
            if(q==1)
            cout<<t<<endl;
            else
            cout<<(b-a+1)-t<<endl;
        }
    }
}

I have optimized it as much as I can. It is still giving memory limit exceeded. Where and how can I optimize this code further in terms of memory ?

History

 
 
 
 
Revisions
 
 
  Rev. Lang. By When Δ Comment
en1 English redgulli 2020-06-05 11:26:03 2176 Initial revision (published)