BIT-- POINT UPDATE AND RANGE QUERY !!!!
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int arr[10000000];
int tree[1000000];
int n;
// build tree
void build(int val,int index)
{
while(index<=n)
{
tree[index]+=val;
index+=index & (-index);
}
}
// increase ith index value by val ..
void update(int val,int index)
{
int diff=val-arr[index];
arr[index]=val;
while(index<=n)
{
tree[index]+=diff;
index+=index & (-index);
}
}
// sum from index 1 to index
int query(int index)
{
int sum=0;
while(index!=0)
{
sum+=tree[index];
index-=index & (-index);
}
return sum;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>arr[i];
}
for(int i=1;i<=n;i++)
{
build(arr[i],i);
}
int q;
cin>>q;
while(q--)
{
int type ;
cin>>type;
if(type==1)
{
cout<<" enter value and index at which need to update !!!!"<<endl;
int val ,index;// index at which need to update if array is 1 based
cin>>val>>index;
update(val,index);
cout<<" tree status "<<endl;
for(int i=1;i<=n;i++) cout<<tree[i]<<" ";
cout<<endl;
}
else
{
int index;
cin>>index;// sum of fist index no of numbers ...
int ans=query(index);
cout<<ans<<endl;
}
}
}
#include<iostream>
using namespace std;
#include<bits/stdc++.h>
int arr[10000000];
int tree[1000000];
int n;
// build tree
void build(int val,int index)
{
while(index<=n)
{
tree[index]+=val;
index+=index & (-index);
}
}
// increase ith index value by val ..
void update(int val,int index)
{
int diff=val-arr[index];
arr[index]=val;
while(index<=n)
{
tree[index]+=diff;
index+=index & (-index);
}
}
// sum from index 1 to index
int query(int index)
{
int sum=0;
while(index!=0)
{
sum+=tree[index];
index-=index & (-index);
}
return sum;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
{
cin>>arr[i];
}
for(int i=1;i<=n;i++)
{
build(arr[i],i);
}
int q;
cin>>q;
while(q--)
{
int type ;
cin>>type;
if(type==1)
{
cout<<" enter value and index at which need to update !!!!"<<endl;
int val ,index;// index at which need to update if array is 1 based
cin>>val>>index;
update(val,index);
cout<<" tree status "<<endl;
for(int i=1;i<=n;i++) cout<<tree[i]<<" ";
cout<<endl;
}
else
{
int index;
cin>>index;// sum of fist index no of numbers ...
int ans=query(index);
cout<<ans<<endl;
}
}
}
No comments:
Post a Comment