using System.Diagnostics;
public class RangeCalculator
private int[] countSmaller;
public RangeCalculator(int K)
countSmaller = new int[K+1];
public void preprocess(int[] a)
int [] count = new int[countSmaller.Length-1];
Trace.Assert(0 <= k && k < count.Length);
for(int i = 1; i < countSmaller.Length; i++)
countSmaller[i] = count[i-1] + countSmaller[i-1];
public int countInRange(int rMin, int rMax)
return countSmaller[rMax+1] - countSmaller[rMin];
public static void Main()
int [] a = new []{ 0, 12, 0, 1, 4, 4, 15, 0};
public static void Test(int[] a, int k, int rmin, int rmax)
RangeCalculator range = new RangeCalculator(k);
int n = range.countInRange(rmin, rmax);
Console.WriteLine("Sequence ({0}) has {1} values in range {2}..{3}", string.Join(" ", a), n, rmin, rmax);