题目链接:
http://acm.nyist.net/JudgeOnline/problem.php?pid=119
解法: RMQ问题。
代码:
#include <stdio.h>
#include <ctime>
#include <math.h>
#include <limits.h>
#include <complex>
#include <string>
#include <functional>
#include <iterator>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <list>
#include <bitset>
#include <sstream>
#include <iomanip>
#include <fstream>
#include <iostream>
#include <cmath>
#include <cstring>
#include <cstdio>
#include <time.h>
#include <ctype.h>
#include <string.h>
#include <assert.h>
using namespace std;
int n, k, p, l, r;
int a[100010];
int s[100010][20];
int maxsum[100010][20], minsum[100010][20];
int rmq(int l, int r)
{
int k = log2((double)(r - l + 1));
int MAX = max(maxsum[l][k], maxsum[r - (1 << k) + 1][k]);
int MIN = min(minsum[l][k], minsum[r - (1 << k) + 1][k]);
return MAX - MIN;
}
int main()
{
int t;
int q;
while (scanf("%d %d", &n, &q)!=EOF)
{
for (int i = 1; i <= n; i++)
{
scanf("%d", &a[i]);
maxsum[i][0] = minsum[i][0] = a[i];
}
for (int j = 1; (1 << j) <= n; j++)
for (int i = 1; i + (1 << j) - 1 <= n; i++)
{
maxsum[i][j] = max(maxsum[i][j - 1], maxsum[i + (1 << (j - 1))][j - 1]);
minsum[i][j] = min(minsum[i][j - 1], minsum[i + (1 << (j - 1))][j - 1]);
}
int s, t;
while (q--)
{
scanf("%d%d",&s,&t);
printf("%d\n", rmq(s, t));
}
}
return 0;
}