Let the array contain the original permutation. Construct an array such that:
For example, if
then
The answer to a query is a[RMQa[u..v]].
Example
Consider the input permutation given by array , and construct the auxiliary array based on it.
For example, the number is located at position in the permutation (that is, b[9] = 1). Therefore, we set a[1] = 9.
Now consider the query (a, b) = (2, 4). The number is at position , the number is at position , and the number is at position . Thus, in array , the elements with indices , and are equal to , and respectively — these are the positions of the numbers , and in the original array .
It remains to find the minimum value in the subarray . It is equal to (the minimum among and ). Therefore, the answer is position .
Algorithm implementation
Declare an array , where mas[i][j] will store the index of the minimum element on the segment (i, ..., i + 2^j - 1). Declare auxiliary arrays and .
#define DIM1 100010
#define DIM2 17
int mas[DIM1][DIM2];
int a[DIM1], b[DIM1];The function Build_RMQ_Array constructs the array based on the array in such a way that
void Build_RMQ_Array(int *b)
{
int i, j;
for (i = 1; i <= n; i++) mas[i][0] = b[i];
for (j = 1; 1 << j <= n; j++)
for (i = 1; i + (1 << j) - 1 <= n; i++)
mas[i][j] = min(mas[i][j - 1], mas[i + (1 << (j - 1))][j - 1]);
}The function RMQ returns the minimum value on the segment (b_i, b_{i+1}, ..., b_j) in time.
int RMQ(int i, int j)
{
int k = 0;
while ((1 << (k + 1)) <= j - i + 1) k++;
return min(mas[i][k],mas[j - (1<<k) + 1][k]);
}Read the input data and store the permutation in the array .
scanf("%d %d",&n,&q);
for (i = 1; i <= n; i++) scanf("%d",&b[i]);Build the array .
for (i = 1; i <= n; i++) a[b[i]] = i;Perform preprocessing to support queries.
Build_RMQ_Array(a);For each query compute and print the answer.
for (i = 0; i < q; i++)
{
scanf("%d %d",&u,&v);
printf("%d\n",RMQ(u,v));
}Java implementation
import java.util.*;
public class Main
{
private final static int DIM1 = 100010;
private final static int DIM2 = 17;
static int[] a = new int[DIM1];
static int[] b = new int[DIM1];
static int[][] mas = new int[DIM1][DIM2];
static int min(int a, int b)
{
return (a < b) ? a : b;
}
static void Build_RMQ_Array(int[] b, int n)
{
int i, j;
for (i = 1; i <= n; i++) mas[i][0] = b[i];
for (j = 1; 1 << j <= n; j++)
for (i = 1; i + (1 << j) - 1 <= n; i++)
mas[i][j] =
min(mas[i][j - 1], mas[i + (1 << (j - 1))][j - 1]);
}
static int RMQ(int i, int j)
{
int k = 0;
while ((1 << (k + 1)) <= j - i + 1) k++;
return min(mas[i][k],mas[j - (1<<k) + 1][k]);
}
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
int i, n = con.nextInt(),
q = con.nextInt();
for (i = 1; i <= n; i++) b[i] = con.nextInt();
for (i = 1; i <= n; i++) a[b[i]] = i;
Build_RMQ_Array(a, n);
for(i = 0; i < q; i++)
{
int u = con.nextInt();
int v = con.nextInt();
System.out.println(RMQ(u,v));
}
}
}