POJ 3264 Balanced Lineup ST表
来源:互联网 发布:手机上传图片asp源码 编辑:程序博客网 时间:2024/05/16 08:46
链接:http://poj.org/problem?id=3264
题意:给一串数字,多次询问,求区间最大值和区间最小值的差。
思路:RMQ问题,可以用O(N^2)的预处理,然后每次O(1)的查询,可以用线段树,O(N)的建树,O(logN)的查询,可以用ST表记录,O(NlogN)的预处理,O(1)的查询。
实际上ST表的预处理过程也是一个DP的过程dp[i][j]表示从第i位开始连续2^j位的区间最值。
预处理:dp[i][j]=min(dp[i][j],dp[i+2^j][j]),查询:query(l,r)=min(dp[l][k],dp[r-2^k+1][k]),k保证2^k<=r-l+1且2^(k+1)>=r-l+1。
代码:
#include <iostream>#include <cstdio>#include <algorithm>#define maxn 50010using namespace std;int stTable_min[maxn][32],stTable_max[maxn][32];int preLog2[maxn],aa[maxn];void st_prepare(int n,int *array){ preLog2[1]=0; for(int i=2; i<=n; i++) { preLog2[i]=preLog2[i-1]; if((1<<preLog2[i]+1)==i) preLog2[i]++; } for(int i=n-1; i>=0; i--) { stTable_min[i][0]=array[i]; stTable_max[i][0]=array[i]; for(int j=1; (i+(1<<j)-1)<n; j++) { stTable_min[i][j]=min(stTable_min[i][j-1],stTable_min[i+(1<<j-1)][j-1]); stTable_max[i][j]=max(stTable_max[i][j-1],stTable_max[i+(1<<j-1)][j-1]); } } return ;}int query_sub(int l,int r){ int len=r-l+1,k=preLog2[len]; return max(stTable_max[l][k],stTable_max[r-(1<<k)+1][k])-min(stTable_min[l][k],stTable_min[r-(1<<k)+1][k]);}int main(){ int n,q; scanf("%d%d",&n,&q); for(int i=0; i<n; i++) scanf("%d",&aa[i]); st_prepare(n,aa); for(int i=0; i<q; i++) { int l,r; scanf("%d%d",&l,&r); printf("%d\n",query_sub(l-1,r-1)); } return 0;}
2 0
- POJ 3264 Balanced Lineup ST表
- poj 3264 Balanced Lineup ST表
- [POJ 3264] Balanced Lineup (ST表)
- POJ 3264 Balanced Lineup(ST表)
- poj 3264 Balanced Lineup ST
- poj 3264 Balanced Lineup(ST)
- poj 3264 Balanced Lineup ST
- Balanced Lineup-POJ - 3264-RMQ线段树/st表
- POJ 3264 Balanced Lineup (ST算法入门)
- POJ 3264 Balanced Lineup ST算法
- poj 3264 Balanced Lineup ST+线段树
- poj 3264 Balanced Lineup ST算法
- POJ 3264 Balanced Lineup(ST)
- Poj 3264 Balanced Lineup【RMQ----ST算法】
- 【POJ】【P3264】【Balanced Lineup】【题解】【ST表】
- RMQ (st表) Balanced Lineup
- poj 3264 Balanced Lineup ( ST算法(dp))
- RMQ的ST算法学习小记 Poj 3264 Balanced Lineup
- LeetCode-Spiral Matrix
- CentOS 6.5 64位 MySQL源码安装
- 呵呵
- poj 2352 && hdu 1541 Stars (树状数组水题)
- linux批处理命令
- POJ 3264 Balanced Lineup ST表
- 为数据挖掘,数据分析师做准备
- 【九度OJ】1048【模拟】
- 延展(Extension)定义用法
- 系统API 实现SQLite增删改 sql事务beginTransaction()
- Codeforces Round #260 (Div. 2) E. Civilization
- 采用XFire调用Java Web Service
- spring mvc 方法注解拦截器
- 【IOS 开发】Object - C 入门 之 数据类型详解