I am trying to solve the problem MATSUM on spoj.I try it using 2D Binary Indexed Tree.But keep getting Time Limit Exceeded.If my approach to solve this problem is not good enough then please suggest another methods.If my approach is correct then please guide me how to get rid-off from TLE.
My code is below
Your code here...
#include<iostream>
#include<cstdio>
#include<vector>
#include<queue>
#include<stack>
#include<utility>
#include<map>
#include<stdlib.h>
#include<string.h>
using namespace std;
#define g getchar_unlocked()
int scan()//fast input output
{
int t=0;
char c;
c=g;
while(c<'0' || c>'9')
c=g;
while(c>='0' && c<='9')
{
t=(t<<3)+(t<<1)+c-'0';
c=g;
}//end fast input output
return(t);
}
vector<int> Matrix[1026];
int N; // MAXVAL for Binary indexed tree tree(1 based indexing)
void initialize()
{
scanf("%d",&N);
for(int i=0;i<N;i++)
Matrix[i].resize(N+2);
return ;
}
int Freq_at_idx(int idx,int vec_idx)
{
int sum=Matrix[vec_idx][idx];
if(idx>0)
{
int z=idx-(idx&-idx);
idx--;
while(idx!=z)
{
sum-=Matrix[vec_idx][idx];
idx-=(idx&-idx);
}
}
return sum;
}
void update(int vec_idx,int idx,int v)
{
while(idx<=N)
{
Matrix[vec_idx][idx]+=v;
idx+=(idx&-idx);
}
return ;
}
// it gives the sum of all the elements from 1 to idx of vector Matrix[vec_idx]
int Cumilative_Freq(int vec_idx,int idx)
{
int sum=0;
while(idx>0)
{
sum+=Matrix[vec_idx][idx];
idx-=(idx&-idx);
}
return sum;
}
void set_value(int x,int y,int v)
{
int v1;
v1=Freq_at_idx(y+1,x);
v=v-v1;
if(v==0)
return ;
update(x,y+1,v);
}
void get_sum(int x1,int y1,int x2,int y2)
{
int sum=0;
for(int i=x1;i<=x2;i++)
{
sum+=Cumilative_Freq(i,y2+1)-Cumilative_Freq(i,y1);
}
printf("%d\n",sum);
return ;
}
int main()
{
int x,y,v,x1,x2,y1,y2;
char str[5];
int tc;
//scanf("%d",&tc);
tc=scan();
while(tc--)
{
initialize();
scanf("%s",str);
while(str[0]!='E')
{
if(str[1]=='E')
{
//scanf("%d%d%d",&x,&y,&v);
x=scan();
y=scan();
v=scan();
set_value(x,y,v);
}
else
{
//scanf("%d%d%d%d",&x1,&y1,&x2,&y2);
x1=scan();
y1=scan();
x2=scan();
y2=scan();
get_sum(x1,y1,x2,y2);
}
scanf("%s",str);
}
for(int i=0;i<N;i++)
Matrix[i].clear();
}
return 0;
}
Hi selfcompiler
This evidently TLE. When coding a 2D BIT, you want the query/update runtimes to be around (log N) ^ 2. In your get_sum method (which is the querying), you have a loop that runs through [x1, x2], which is linear. This makes querying N log N.
I recommend reading this topcoder blog: http://community.topcoder.com/tc?module=Static&d1=tutorials&d2=binaryIndexedTrees . It explains quite clearly on how to code 1D/2D BIT's in a clean and efficient way. Your code for this should be no longer than 50 lines.
Let me know if you are still stuck
thanx bboy_drain i understand it :)
Hii bboy_drain i tried to impliment this but now i am getting WA , i try this problem from last 4 days . I am not able to find out the bug in my code would you like to take a look at my new code ?