// C# program to implement
// the above approach
using System;
public class GFG
{
// Function to update the array elements
// at idx pos, i.e arr[pos] += X
static void update(int []Tree, int idx, int s,
int e, int pos, int X)
{
// If current node is a
// leaf nodes
if (s == e)
{
// Update Tree[idx]
Tree[idx] += X;
}
else
{
// Divide segment tree into left
// and right subtree
int m = (s + e) / 2;
// Check if pos lies in left subtree
if (pos <= m)
{
// Search pos in left subtree
update(Tree, 2 * idx, s, m, pos, X);
}
else
{
// Search pos in right subtree
update(Tree, 2 * idx + 1, m + 1, e,
pos, X);
}
// Update Tree[idx]
Tree[idx]
= Tree[2 * idx] + Tree[2 * idx + 1];
}
}
// Function to find the sum from
// elements in the range [0, X]
static int sum(int []Tree, int idx, int s,
int e, int ql, int qr)
{
// Check if range[ql, qr] equals
// to range [s, e]
if (ql == s && qr == e)
return Tree[idx];
if (ql > qr)
return 0;
// Divide segment tree into
// left subtree and
// right subtree
int m = (s + e) / 2;
// Return sum of elements in the range[ql, qr]
return sum(Tree, 2 * idx, s, m, ql, Math.Min(m, qr))
+ sum(Tree, 2 * idx + 1, m + 1, e,
Math.Max(ql, m + 1), qr);
}
// Function to find Xth element
// in the array
static void getElement(int []Tree, int X, int N)
{
// Print element at index x
Console.Write("Element at " + X+ " is "
+ sum(Tree, 1, 0, N - 1, 0, X) +"\n");
}
// Function to update array elements
// in the range [L, R]
static void range_Update(int []Tree, int L,
int R, int X, int N)
{
// Update arr[l] += X
update(Tree, 1, 0, N - 1, L, X);
// Update arr[R + 1] += X
if (R + 1 < N)
update(Tree, 1, 0, N - 1, R + 1, -X);
}
// Drivers Code
public static void Main(String[] args)
{
// Size of array
int N = 5;
int []Tree = new int[4 * N + 5];
int []arr = { 0, 0 };
int[,]Q = { { 1, 0, 1, 100 }, { 2, 1, 0, 0 } };
int cntQuery = Q.GetLength(0);
for (int i = 0; i < cntQuery; i++)
{
if (Q[i, 0] == 1)
{
range_Update(Tree, Q[i, 1],
Q[i, 2], Q[i, 3], N);
}
else
{
getElement(Tree, Q[i, 1], N);
}
}
}
}
// This code is contributed by 29AjayKumar