Saturday 17 March 2018

Square Root Decomposition to Solve Sum of array elements Range Queries in Competitive Programming

#include<iostream>
#include<cmath>
using namespace std;

int main() {
  int a[] ={1,5,2,4,6,1,3,5,7},n=9;  
  int bs=sqrt(n); //block_size
  int nob=ceil((double)n/bs);//number of blocks
  int res[nob],j=0,sum; //res array stores the block sum
  //printf("%d",nob);
  for(int i=0;i<nob;i++)
  {
      sum=0;
      for(int c=0;c<bs;c++,j++)
        sum=sum+a[j];
      res[i]=sum;  //updating block sum
  }
 //for(int i=0;i<nob;i++)
 //cout<<res[i]<<" ";
  int noq,ad,b_id;
  cin>>noq;
  while(noq--)
  {
      int l,r,opt;
      cin>>opt>>l>>r;
    // l--;r--;     
      switch(opt)
      {
          case 1: b_id=l/bs;
                  res[b_id]=res[b_id]-a[l]+r;
                  a[l]=r;
                  break;
          case 2:  ad=0;
                    while(l<r && l%bs != 0 && l!=0 ){
                        ad=ad+a[l];l++;}

                     while(l+bs-1<=r)
                    {
                        ad=ad+res[l/bs];  //l/bs will give the block index
                        l=l+bs;
                        // cout<<ad<<endl;
                    }
                    for(;l<=r;l++)
                        ad=ad+a[l];
                     cout<<ad<<endl;
      }

 }
  return 0;
}

No comments:

Post a Comment