# NYOJ-119 士兵杀敌（三）【RMQ算法】

RMQ算法。

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

const int N = 100010;
int maxsum[N][20], minsum[N][20];

void RMQ(int num) //预处理->O(nlogn)
{
for(int j = 1; j < 20; ++j)
for(int i = 1; i <= num; ++i)
if(i + (1 << j) - 1 <= num)
{
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 main()
{
int num, query;
int src, des;
scanf("%d %d", &num, &query);
for(int i = 1; i <= num; ++i) //输入信息处理
{
scanf("%d", &maxsum[i][0]);
minsum[i][0] = maxsum[i][0];
}
RMQ(num);
while(query--) //O(1)查询
{
scanf("%d %d", &src, &des);
int k = (int)(log(des - src + 1.0) / log(2.0));
int maxres = max(maxsum[src][k], maxsum[des - (1 << k) + 1][k]);
int minres = min(minsum[src][k], minsum[des - (1 << k) + 1][k]);
printf("%d\n", maxres - minres);
}
return 0;
}

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

const int N = 100010;
int maxsum[20][N], minsum[20][N]; //优化1

void RMQ(int num) //预处理->O(nlogn)
{
for(int i = 1; i != 20; ++i)
for(int j = 1; j <= num; ++j)
if(j + (1 << i) - 1 <= num)
{
maxsum[i][j] = max(maxsum[i - 1][j], maxsum[i - 1][j + (1 << i >> 1)]); //优化2
minsum[i][j] = min(minsum[i - 1][j], minsum[i - 1][j + (1 << i >> 1)]);
}
}

int main()
{
int num, query;
int src, des;
scanf("%d %d", &num, &query);
for(int i = 1; i <= num; ++i) //输入信息处理
{
scanf("%d", &maxsum[0][i]);
minsum[0][i] = maxsum[0][i];
}
RMQ(num);
while(query--) //O(1)查询
{
scanf("%d %d", &src, &des);
int k = (int)(log(des - src + 1.0) / log(2.0));
int maxres = max(maxsum[k][src], maxsum[k][des - (1 << k) + 1]);
int minres = min(minsum[k][src], minsum[k][des - (1 << k) + 1]);
printf("%d\n", maxres - minres);
}
return 0;
}

• 本文已收录于以下专栏：

举报原因： 您举报文章：NYOJ-119 士兵杀敌（三）【RMQ算法】 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)