Skip to content

Instantly share code, notes, and snippets.

@theoremoon
Created April 3, 2020 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save theoremoon/6d09aba0154cb53c1871067ae78ce754 to your computer and use it in GitHub Desktop.
Save theoremoon/6d09aba0154cb53c1871067ae78ce754 to your computer and use it in GitHub Desktop.
import std.stdio, std.string, std.algorithm, std.array, std.range, std.conv,
std.typecons, std.math, std.container, std.format, std.numeric;
class SegmentTree
{
private:
long[] xs;
long size;
public:
this(long size)
{
long i = 1;
while (i <= size)
{
i *= 2;
}
this.size = size;
this.xs = new long[](i * 2);
}
void add(long l, long r, long x)
{
l += this.size;
r += this.size;
while (l < r)
{
if (l % 2 == 1)
{
xs[l] += x;
l++;
}
l /= 2;
if (r % 2 == 1)
{
xs[r - 1] += x;
r--;
}
r /= 2;
}
}
long get(long i)
{
i += this.size;
long ans = xs[i];
while (true)
{
i /= 2;
if (i == 0)
{
break;
}
ans += xs[i];
}
return ans;
}
}
void main(string[] args)
{
long n, q;
readf("%d %d\n", &n, &q);
auto seg = new SegmentTree(n);
foreach (i; 0 .. q)
{
long cmd, s, t, x;
readf("%d ", &cmd);
if (cmd == 0)
{
readf("%d %d %d\n", &s, &t, &x);
seg.add(s, t + 1, x);
}
else
{
readf("%d\n", &x);
writeln(seg.get(x));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment