Advertisement
KennasSticky

MinimumQuery

Jun 19th, 2021
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1. import java.util.*;
  2. import java.io.*;
  3.  
  4. public class MinimumQuery {
  5.  
  6.   static int[][] mem;
  7.   static int[] arr;
  8.   public static void main(String[] args) {
  9.     Scanner scan = new Scanner(System.in);
  10.  
  11.     int n = scan.nextInt();
  12.  
  13.     arr = new int[n];
  14.     int j = getfloor(n);
  15.     mem = new int[n][500];
  16.    
  17.     // Standard IO Routine
  18.     for (int i = 0; i < n; i++) {
  19.       arr[i] = scan.nextInt();
  20.     }
  21.  
  22.     // call precalculation function  
  23.     mini(n);
  24.  
  25.     int t = scan.nextInt();
  26.  
  27.     while (t-- > 0) {
  28.       int a = scan.nextInt();
  29.       int b = scan.nextInt();
  30.  
  31.       System.out.println(search(a,b));
  32.     }
  33.   }
  34.  
  35.   static int search(int a, int b) {
  36.     int k = getfloor(b-a+1);
  37.  
  38.     return Math.min(mem[a][k-1], mem[b-(1 << (k-1))][k-1]);
  39.   }
  40.  
  41.   static void mini(int n) {
  42.      
  43.     // fill in ranges of length 1 initially  
  44.     for (int i = 0; i < arr.length; i++) mem[i][0] = arr[i];
  45.  
  46.     // number of lengths that are powers of 2 -> Using bitshifts to generate the powers of 2
  47.     for (int i = 1; (1 << i) <= n; i++) {
  48.       for (int j = 0; j + (1 << i) - 1 < n; j++) {
  49.         mem[j][i] = Math.min(mem[j][i-1], mem[j + (1 << (i - 1))][i - 1]);
  50.       }
  51.     }  
  52.   }
  53.  
  54.   // returns the greatest power of 2 smaller than n  
  55.   static int getfloor(int n) {
  56.     int i = 0;
  57.     if (n == 1) return 0;
  58.     while (Math.pow(2, i) <= n) {
  59.       i++;
  60.     }
  61.     return i-1;
  62.   }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement