BZOJ1636&&1699:[USACO2007JAN]Balanced Lineup

浅谈\(RMQ\)https://www.cnblogs.com/AKMer/p/10128219.html

题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1636

题目传送门:https://lydsy.com/JudgeOnline/problem.php?id=1699

裸的\(RMQ\)

时间复杂度:\(O(nlogn+m)\)

空间复杂度:\(O(nlogn)\)

代码如下:

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

const int maxn=5e4+5;

int n,m;
int a[maxn],Log[maxn];
int f[17][maxn],g[17][maxn];

int read() {
	int x=0,f=1;char ch=getchar();
	for(;ch<'0'||ch>'9';ch=getchar())if(ch=='-')f=-1;
	for(;ch>='0'&&ch<='9';ch=getchar())x=x*10+ch-'0';
	return x*f;
}

void make_st() {
	Log[0]=-1;
	for(int i=1;i<=n;i++)
		Log[i]=Log[i>>1]+1;
	for(int i=1;i<17;i++)
		for(int j=1;j+(1<<i)-1<=n;j++) {
			f[i][j]=max(f[i-1][j],f[i-1][j+(1<<(i-1))]);
			g[i][j]=min(g[i-1][j],g[i-1][j+(1<<(i-1))]);
		}
}

int query(int l,int r) {
	int x=Log[r-l+1];
	int mx=max(f[x][l],f[x][r-(1<<x)+1]);
	int mn=min(g[x][l],g[x][r-(1<<x)+1]);
	return mx-mn;
}

int main() {
	n=read(),m=read();
	for(int i=1;i<=n;i++)
		f[0][i]=g[0][i]=a[i]=read();
	make_st();
	for(int i=1;i<=m;i++) {
		int l=read(),r=read();
		printf("%d\n",query(l,r));
	}
	return 0;
}
posted @ 2019-01-08 21:47  AKMer  阅读(125)  评论(0编辑  收藏  举报