using
System;
using
System.Collections.Generic;
class
GFG
{
static
readonly
int
N = 100005;
static
int
[]arr = { 0, 1, 2, 2, 1, 4, 3, 6 };
static
List<
int
> []tree =
new
List<
int
>[N];
static
int
idx;
static
int
[]tin =
new
int
[N];
static
int
[]tout =
new
int
[N];
static
int
[]converted =
new
int
[N];
static
void
dfs(
int
node,
int
parent)
{
++idx;
converted[idx] = node;
tin[node] = idx;
foreach
(
int
i
in
tree[node])
{
if
(i != parent)
dfs(i, node);
}
tout[node] = idx;
}
static
int
[]t =
new
int
[N * 4];
static
void
build(
int
node,
int
start,
int
end)
{
if
(start == end)
t[node] = arr[converted[start]];
else
{
int
mid = (start + end) >> 1;
build(2 * node, start, mid);
build(2 * node + 1, mid + 1, end);
t[node] = t[2 * node] + t[2 * node + 1];
}
}
static
void
update(
int
node,
int
start,
int
end,
int
lf,
int
rg,
int
c)
{
if
(start > end || start > rg || end < lf)
return
;
if
(start == end)
{
t[node] = c;
}
else
{
int
mid = (start + end) >> 1;
update(2 * node, start, mid, lf, rg, c);
update(2 * node + 1, mid + 1, end, lf, rg, c);
t[node] = t[2 * node] + t[2 * node + 1];
}
}
static
int
query(
int
node,
int
start,
int
end,
int
lf,
int
rg)
{
if
(start > rg || end < lf)
return
0;
if
(lf <= start && end <= rg)
{
return
t[node];
}
else
{
int
ans = 0;
int
mid = (start + end) >> 1;
ans += query(2 * node, start, mid, lf, rg);
ans += query(2 * node + 1, mid + 1,
end, lf, rg);
return
ans;
}
}
static
void
printTree(
int
q,
int
node,
int
n)
{
while
(q-- > 0)
{
int
lf = tin[node];
int
rg = tout[node];
int
res = query(1, 1, n, lf, rg);
Console.Write(
"sum at node "
+ node
+
": "
+ res +
"\n"
);
node++;
}
}
public
static
void
Main(String[] args)
{
int
n = 7;
for
(
int
i = 0; i < N; i++)
tree[i] =
new
List<
int
>();
tree[1].Add(2);
tree[1].Add(3);
tree[1].Add(4);
tree[3].Add(5);
tree[3].Add(6);
tree[3].Add(7);
idx = 0;
dfs(1, -1);
build(1, 1, n);
printTree(7, 1, 7);
int
node = 3;
int
lf = tin[node];
int
rg = tout[node];
int
value = 4;
update(1, 1, n, lf, rg, value);
Console.Write(
"After Update"
+
"\n"
);
printTree(7, 1, 7);
}
}