欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

51Nod - 1174 RMQ算法

程序员文章站 2022-05-11 14:13:39
...
给出一个有N个数的序列,编号0 - N - 1。进行Q次查询,查询编号i至j的所有数中,最大的数是多少。
例如: 1 7 6 3 1。i = 1, j = 3,对应的数为7 6 3,最大的数为7。(该问题也被称为RMQ问题)
Input第1行:1个数N,表示序列的长度。(2 <= N <= 10000) 
第2 - N + 1行:每行1个数,对应序列中的元素。(0 <= Sii <= 10^9) 
第N + 2行:1个数Q,表示查询的数量。(2 <= Q <= 10000) 
第N + 3 - N + Q + 2行:每行2个数,对应查询的起始编号i和结束编号j。(0 <= i <= j <= N - 1)Output共Q行,对应每一个查询区间的最大值。Sample Input
5
1
7
6
3
1
3
0 1
1 3
3 4
Sample Output
7
7
3

直接就是rmq算法,如果不熟悉的话可以看http://www.voidcn.com/article/p-cobdcwbo-bgk.html

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
int f[11111][15],a[11111];
void RMQ(int num)
{
	int i,j;
	for(i=1;i<=num;i++) f[i][0]=a[i];
	for(j=1;j<=15;j++) {
		for(i=1;i<=num;i++)
		if(i+(1<<j)-1<=num) {
			f[i][j]=max(f[i][j-1],f[i+(1<<(j-1))][j-1]);
		}
	}
}
int main()
{
	 ios::sync_with_stdio(false);
	int n,i,j,q,l,r,k;
	cin>>n;
	for(i=1;i<=n;i++) cin>>a[i];
	RMQ(n);
	cin>>q;
	while(q--) {
		cin>>l>>r;
		l++;r++;
		k=log2(r-l+1);
		cout<<max(f[l][k],f[r-(1<<k)+1][k])<<endl;
	}
	return 0;
}
当然也可以当水题ac过,序列不大
#include <algorithm>
#include <iostream>
#include <cstring>
#include <cstdio>

#define INF 0x7fffffff
using namespace std;

int i,j,n,s[10001],maxn,Q;
int max(int a,int b)
{
    return a>b?a:b;
}
int main()
{
    cin>>n;
    for(i=0;i<n;++i)
    cin>>s[i];
    cin>>Q;
    int u,v;
    while(Q--)
    {
        cin>>u>>v;
        maxn=-INF;
        for(i=u;i<=v;++i)
        maxn=max(maxn,s[i]);
        cout<<maxn<<endl;
    }
    return 0;
}