Skip to content

Instantly share code, notes, and snippets.

@shobhit6993
Created October 25, 2013 03:59
Show Gist options
  • Save shobhit6993/7149273 to your computer and use it in GitHub Desktop.
Save shobhit6993/7149273 to your computer and use it in GitHub Desktop.
Another implementation of segment tree with lazy propagation with sum of intervals operation
#include <cstdio>
#include <iostream>
#include <string.h>
using namespace std;
#define l(n) 2*n
#define r(n) 2*n+1
#define rep(i,a,b) for(i = a;i<=b;i++)
#define SIZE 262145
#define MAX 131072
typedef long long ll;
long long memo[SIZE];
long long lazy[SIZE];
void update(ll nd,ll s,ll e,ll p,ll q,ll v)
{
if(e<p || s>q || s>e)
return;
if(s >= p && e <= q)
{
memo[nd] += (e-s+1) * v;
if(s!=e)
{
lazy[l(nd)]+=v;
lazy[r(nd)]+=v;
}
return;
}
update(l(nd),s,(s+e)/2,p,q,v);
update(r(nd),(s+e)/2+1,e,p,q,v);
memo[nd] += (min(q,e) - max(s,p) + 1) * v;
}
long long query(ll nd,ll s,ll e,ll p,ll q)
{
if(e<p || s>q || e<s)
return 0;
if(lazy[nd] != 0)
{
memo[nd]+=(e-s+1)*lazy[nd];
if(s!=e)
{
lazy[l(nd)] += lazy[nd];
lazy[r(nd)] += lazy[nd];
}
lazy[nd] = 0;
}
if(s >= p && e <= q)
return memo[nd];
return query(l(nd),s,(s+e)/2,p,q) + query(r(nd),(s+e)/2+1,e,p,q);
}
int main()
{
ll t,n,c,p,q,v,i,cs;
cin >> t;
while(t--)
{
memset(memo,0,sizeof(memo));
memset(lazy,0,sizeof(lazy));
cin >> n >> c;
rep(i,1,c)
{
cin >> cs >> p >> q;
if(cs)
cout << query(1,1,MAX,p,q) << "\n";
else
{
cin >> v;
update(1,1,MAX,p,q,v);
}
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment