3264Balanced Lineuprmq

    技术2022-05-20  61

    Balanced Lineup Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 16743 Accepted: 7758Case Time Limit: 2000MS

    Description

    For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

    Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

    Input

    Line 1: Two space-separated integers,  N and  Q.  Lines 2.. N+1: Line  i+1 contains a single integer that is the height of cow  i  Lines  N+2.. N+ Q+1: Two integers  A and  B (1 ≤  A ≤  B ≤  N), representing the range of cows from  A to  B inclusive.

    Output

    Lines 1.. Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

    Sample Input

    6 3 1 7 3 4 2 5 1 5 4 6 2 2

    Sample Output

    6 3 0

    Source

    USACO 2007 January Silver

     

    /* RMQ问题是求给定区间中的最值问题,专门对于查询次数很大的,O(n)的算法效率不够。 虽然可以用线段树将算法优化到O(logn)(在线段树中保存线段的最值),不过每次线段树查询时O(LOG(N)) 不过,Sparse_Table算法才是最好的:它可以在O(nlogn)的预处理以后实现O(1)的查询效率。 预处理: 预处理使用DP的思想,f(i, j)表示[i, i+2^j - 1]区间中的最小值,我们可以开辟一个数组专门来保存f(i, j)的值。 例如,f(0, 0)表示[0,0]之间的最小值,就是num[0], f(0, 2)表示[0, 3]之间的最小值, f(2, 4)表示[2, 17]之间的最小值 注意, 因为f(i, j)可以由f(i, j - 1)和f(i+2^(j-1), j-1)导出, 而递推的初值(所有的f(i, 0) = i)都是已知的 查询: 假设要查询从m到n这一段的最小值, 那么我们先求出一个最大的k, 使得k满足2^k <= (n - m + 1). 于是我们就可以把[m, n]分成两个(部分重叠的)长度为2^k的区间: [m, m+2^k-1], [n-2^k+1, n]; 而我们之前已经求出了f(m, k)为[m, m+2^k-1]的最小值, f(n-2^k+1, k)为[n-2^k+1, n]的最小值 */ #include<cstdio> #include<cmath> using namespace std; #define MAXN 50010 #define mmin(a, b) ((a)<=(b)?(a):(b)) #define mmax(a, b) ((a)>=(b)?(a):(b)) int num[MAXN]; int f1[MAXN][20]; int f2[MAXN][20]; //sparse table算法 void st(int n) { int i, j, k, m; k = (int) (log((double)n) / log(2.0)); for(i = 0; i < n; i++) { f1[i][0] = num[i]; //递推的初值 f2[i][0] = num[i]; } for(j = 1; j <= k; j++) { //自底向上递推 for(i = 0; i + (1 << j) - 1 < n; i++) { m = i + (1 << (j - 1)); //求出中间的那个值 f1[i][j] = mmax(f1[i][j-1], f1[m][j-1]); f2[i][j] = mmin(f2[i][j-1], f2[m][j-1]); } } } //查询i和j之间的最值,注意i是从0开始的 void rmq(int i, int j) { int k = (int)(log(double(j-i+1)) / log(2.0)), t1, t2; //用对2去对数的方法求出k t1 = mmax(f1[i][k], f1[j - (1<<k) + 1][k]); t2 = mmin(f2[i][k], f2[j - (1<<k) + 1][k]); printf("%d/n",t1 - t2); } int main() { int N,Q; while(scanf("%d%d",&N,&Q)!=EOF) { for(int i=0;i<N;++i) scanf("%d",&num[i]); st(N); while(Q--) { int a,b; scanf("%d%d",&a,&b); rmq(a-1,b-1); } } return 0; }  


    最新回复(0)