Balanced Lineup poj 3264
来源:互联网 发布:js async 编辑:程序博客网 时间:2024/06/02 06:02
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
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
Sample Input
6 31734251 54 62 2
Sample Output
630
这个题就是典型的RMQ的模板题目
让我们找区间最大值与最小值的差
我们就用RMQ算法,其时间复杂度为O(nlogn), 那有人可能会问我们一次遍历找最大值与最小值所用的时间也就是O(n)的时间复杂度,那为什么我们还要用RMQ呢
这里我还有补充一点,其查找效率为O(1),也就是说我们经过O(nlogn)时间就会解决所有的最大值与最小值的问题了,这样时间复杂度不会因为查找区间的增加而明显增加,
而我们遍历会明显增加增加到O(mn)的时间复杂度上,这里只要m稍微大点都会使算法时间上大大的增加
代码如下:
#include <cstring>#include <cstdio>#include <iostream>#include <algorithm>#define M 50010using 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])); } }}
代码菜鸟,如有错误,请多包涵!!!
如有帮助记得支持我一下,谢谢!!!
- POJ 3264 Balanced Lineup
- POJ 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- Poj 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- POJ-3264-Balanced Lineup
- poj 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- POJ 3264-Balanced Lineup
- poj 3264 Balanced Lineup
- POJ 3264 Balanced Lineup
- POJ-3264-Balanced Lineup
- POJ 3264 Balanced Lineup
- POJ 3264 Balanced Lineup
- poj 3264 Balanced Lineup
- 金税盘发票查询系统
- SSL P1761 城市问题
- 安装pydev的版本匹配
- c++计算一个TXT文件的行数
- windows 下Git服务器搭建
- Balanced Lineup poj 3264
- jvm-之类加载
- muduo库的Logger及附属类剖析
- 再不用ES6就Out了--Promise解决回调地狱
- Cocos2d-x 3 版本的新特性(相对于2.)
- 买票简易版
- orabase
- 极光推送(JPush)集成
- 博客转移了~