当前位置: 代码迷 >> 综合 >> Balanced Lineup poj 3264
  详细解决方案

Balanced Lineup poj 3264

热度:92   发布时间:2023-10-23 08:36:29.0

Balanced Lineup
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 49351   Accepted: 23113
Case 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

这个题就是典型的RMQ的模板题目

让我们找区间最大值与最小值的差

我们就用RMQ算法,其时间复杂度为O(nlogn), 那有人可能会问我们一次遍历找最大值与最小值所用的时间也就是O(n)的时间复杂度,那为什么我们还要用RMQ呢

这里我还有补充一点,其查找效率为O(1),也就是说我们经过O(nlogn)时间就会解决所有的最大值与最小值的问题了,这样时间复杂度不会因为查找区间的增加而明显增加,

而我们遍历会明显增加增加到O(mn)的时间复杂度上,这里只要m稍微大点都会使算法时间上大大的增加


代码如下:

#include <cstring>
#include <cstdio>
#include <iostream>
#include <algorithm>
#define M 50010
using namespace std;int mi[50010][30], ma[50010][30];int main()
{int n, m, x, y, i, j;while ( ~scanf ( "%d %d", &n, &m ) ){for ( i = 1;i <= n; i++ ){scanf ( "%d", &ma[i][0] );mi[i][0] = ma[i][0];}for ( j = 1;(1<<j) <= n; j++ ){for ( i = 1;i+(1<<(j-1)) <= n; i++ ){ma[i][j] = max(ma[i][j-1], ma[i+(1<<(j-1))][j-1]);mi[i][j] = min(mi[i][j-1], mi[i+(1<<(j-1))][j-1]);}}for ( i = 0;i < m; i++ ){scanf ( "%d %d", &x, &y );int nb = 0;while ( (1<<nb) <= y-x+1 )nb++;printf ( "%d\n", max(ma[x][nb-1], ma[y-(1<<(nb-1))+1][nb-1])-min(mi[x][nb-1], mi[y-(1<<(nb-1))+1][nb-1]));}}
}

代码菜鸟,如有错误,请多包涵!!!

如有帮助记得支持我一下,谢谢!!!