Sparse Table (ST) algorithm

package RMQ_LCA;

import java.util.Scanner;

public class SparseTable {
	public static void main(String[] args) {

		int N = 10;
		int[][] M = new int[N][N];
		int[] A = { 2, 4, 3, 1, 6, 7, 8, 9, 1, 7 };
		process(M, A, N);
		Scanner sc = new Scanner(System.in);

		while (true) {
			int i = sc.nextInt();
			int j = sc.nextInt();
			System.out.println(RMQ(M, A, i, j));
		}
	}

	public static int RMQ(int[][] M, int[] A, int i, int j) {

		int k = (int) Math.log(j - i + 1);
		if (A[M[i][k]] <= A[M[j - (1 << k) + 1][k]])
			return M[i][k];
		else
			return M[j - (1 << k) + 1][k];
	}

	public static void process(int[][] M, int[] A, int N) {

		// initialize M for the intervals of length one
		for (int i = 0; i < N; i++)
			M[i][0] = i;
		// compute values from smaller to bigger
		for (int j = 1; 1 << j <= N; j++) {
			// System.out.println(1 << j);
			for (int i = 0; i + (1 << j) - 1 < N; i++) {
				// System.out.println(i + (1 << j) - 1);
				// System.out.println(i + (1 << (j - 1)));
				if (A[M[i][j - 1]] < A[M[i + (1 << (j - 1))][j - 1]])
					M[i][j] = M[i][j - 1];
				else
					M[i][j] = M[i + (1 << (j - 1))][j - 1];
				// System.out.println(1 << (j - 1));
			}

		}
	}

}

Posted on February 4, 2012, in Range Minimum Query and Lowest Common Ancestor, Top Coder. Bookmark the permalink. 2 Comments.

  1. Allah yebareklak 😀

  2. Hi, you are using N^2 of memory. You can change it (to N log N) just by putting

    int M[][] = new int[N][(int)Math.ceil(Math.log(N)/Math.log(2))];

    🙂

Leave a comment