http://acm.hust.edu.cn/vjudge/problem/viewProblem.action?id=23846
题解:
1. 游程编码(将序列转化为(value, num)的一段一段的键值对形式)后,将问题转化为几乎是一个RMQ问题,仅有一些细节要单独考虑
2. 如果查询的两个下标l, r属于同一段键值对,那么答案就是(r - l + 1);否则,答案是三个(或两个)值的最大值,详情见代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string> #define INF 0x3f3f3f3f using namespace std; const int MAXN = 100000 + 5, MAXK = 17 + 5; int d[MAXN][MAXK]; int val[MAXN], num[MAXN]; int id[MAXN], L[MAXN], R[MAXN]; int size; void build(int n) { for(int i=1; i<=n; i++) { d[i][0] = num[i]; } for(int j=1; (1<<j) <= n; j++) { for(int i=1; i + (1 << j) - 1 <= n; i++) { d[i][j] = max(d[i][j-1], d[i+(1<<(j-1))][j-1]); } } } int query(int l, int r) { if(l>r) return -INF; // 是必要的,因为仔细考虑一下,是有可能出现该异常的! int w = r - l + 1; int x = 0; while((1<<x+1) <= w) x++; return max(d[l][x], d[r-(1<<x)+1][x]); } int main () { int n, q, l, r; while(scanf("%d", &n) != EOF && n) { scanf("%d", &q); size = 1; int pre, x; for(int i=1; i<=n; i++) { scanf("%d", &x); if(i==1) { val[size] = x; num[size] = 1; id[i] = size; L[size] = i; } else if(x != pre) { R[size] = i-1; size++; val[size] = x; num[size] = 1; id[i] = size; L[size] = i; } else { num[size]++; id[i] = size; } pre = x; } R[size] = n; build(size); while(q--) { scanf("%d%d", &l, &r); int maxn; if(id[l] == id[r]) { maxn = r - l + 1; } else { maxn = R[id[l]] - l + 1; maxn = max(maxn, r - L[id[r]] + 1); maxn = max(maxn, query(id[l]+1, id[r]-1)); } printf("%d\n", maxn); } } return 0; }