题目地址:点击打开链接
区间最值查询,RMQ和线段树都可以。
RMQ代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 1e5+5;
int mm[maxn], val[maxn], dpMax[maxn][20], dpMin[maxn][20], n, q;
void initRMQ()
{
for(int i = 1; i <= n; i++)
dpMax[i][0] = dpMin[i][0] = val[i];
for(int j = 1; j <= mm[n]; j++)
for(int i = 1; i+(1<<j)-1 <= n; i++)
{
dpMax[i][j] = max(dpMax[i][j-1], dpMax[i+(1<<(j-1))][j-1]);
dpMin[i][j] = min(dpMin[i][j-1], dpMin[i+(1<<(j-1))][j-1]);
}
}
int RMQ(int l, int r)
{
int k = mm[r-l+1];
return max(dpMax[l][k], dpMax[r-(1<<k)+1][k])-min(dpMin[l][k], dpMin[r-(1<<k)+1][k]);
}
int main(void)
{
mm[0] = -1;
for(int i = 1; i < maxn; i++)
mm[i] = ((i&(i-1))==0) ? mm[i-1]+1 : mm[i-1];
while(cin >> n >> q)
{
for(int i = 1; i <= n; i++)
scanf("%d", &val[i]);
initRMQ();
while(q--)
{
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", RMQ(l, r));
}
}
return 0;
}
线段树代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 5e4+5;
const int INF = 0x3f3f3f3f;
int treeMax[maxn*4], treeMin[maxn*4], n, m, Min, Max;
void built(int root, int l, int r)
{
if(l == r)
{
scanf("%d", &treeMax[root]);
treeMin[root] = treeMax[root];
return ;
}
int mid = (l+r)/2;
built(root*2, l, mid);
built(root*2+1, mid+1, r);
treeMax[root] = max(treeMax[root*2], treeMax[root*2+1]);
treeMin[root] = min(treeMin[root*2], treeMin[root*2+1]);
}
void query(int root, int l, int r, int i, int j)
{
if(i <= l && j >= r)
{
Max = max(treeMax[root], Max);
Min = min(treeMin[root], Min);
return ;
}
int mid = (l+r)/2;
if(mid >= i) query(root*2, l, mid, i, j);
if(mid < j) query(root*2+1, mid+1, r, i, j);
}
int main(void)
{
while(cin >> n >> m)
{
memset(treeMax, 0, sizeof(treeMax));
memset(treeMin, 0, sizeof(treeMin));
built(1, 1, n);
while(m--)
{
int l, r;
Min = INF, Max = -INF;
scanf("%d%d", &l, &r);
query(1, 1, n, l, r);
printf("%d\n", Max-Min);
}
}
return 0;
}
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 51434 | Accepted: 24112 | |
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
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 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
Source