2using System.Collections.Generic;
6using System.Threading.Tasks;
62 if (nCapacity <= 0 || (nCapacity % 2) != 0)
63 throw new Exception(
"The capacity must be positive and a power of 2.");
75 private double operation(
double f1,
double f2)
80 return Math.Min(f1, f2);
86 throw new Exception(
"Unknown operation '" +
m_op.ToString() +
"'!");
90 private double reduce_helper(
int nStart,
int nEnd,
int nNode,
int nNodeStart,
int nNodeEnd)
94 Trace.WriteLine(
"**SegmentTree: nEnd is less than zero and should not be.");
98 if (nStart == nNodeStart && nEnd == nNodeEnd)
101 int nMid = (nNodeStart + nNodeEnd) / 2;
105 return reduce_helper(nStart, nEnd, 2 * nNode, nNodeStart, nMid);
109 if (nMid + 1 <= nStart)
111 return reduce_helper(nStart, nMid, 2 * nNode + 1, nMid + 1, nNodeEnd);
115 double f1 = reduce_helper(nStart, nMid, 2 * nNode, nNodeStart, nMid);
116 double f2 = reduce_helper(nMid + 1, nEnd, 2 * nNode + 1, nMid + 1, nNodeEnd);
117 return operation(f1, f2);
129 public double reduce(
int nStart,
int? nEnd =
null)
139 return reduce_helper(nStart, nEnd.Value, 1, 0,
m_nCapacity - 1);
147 public double this[
int nIdx]
152 throw new Exception(
"The index is out of range!");
192 public double sum(
int nStart = 0,
int? nEnd =
null)
194 return reduce(nStart, nEnd);
208 throw new Exception(
"The prefix sum must be greater than zero.");
210 double fSum =
sum() + 1e-5;
211 if (fPrefixSum > fSum)
212 throw new Exception(
"The prefix sum cannot exceed the overall sum of '" + fSum.ToString() +
"'!");
242 : base(nCapacity,
OPERATION.MIN, float.MaxValue)
252 public double min(
int nStart = 0,
int? nEnd =
null)
254 return reduce(nStart, nEnd);
The MinSegmentTree performs a reduction over the array and returns the minimum value.
MinSegmentTree(int nCapacity)
The constructor.
double min(int nStart=0, int? nEnd=null)
Returns the minimum element in the array.
Segment tree data structure
int m_nCapacity
Specifies the capacity of the segment tree.
SegmentTree(int nCapacity, OPERATION oper, float fNeutralElement)
The constructor.
double[] m_rgfValues
Specifies the data of the tree.
OPERATION m_op
Specifies the operation to perform when reducing the tree.
double reduce(int nStart, int? nEnd=null)
Returns result of applying self.operation to a contiguous subsequence of the array....
OPERATION
Specifies the operations used during the reduction.
The SumSegmentTree provides a sum reduction of the items within the array.
int find_prefixsum_idx(double fPrefixSum)
Finds the highest indes 'i' in the array such that sum(arr[0] + arr[1] + ... + arr[i-1]) less than or...
SumSegmentTree(int nCapacity)
The constructor.
double sum(int nStart=0, int? nEnd=null)
Returns arr[start] + ... + arr[end]