本题很明显是线段树。
关键怎么求出区间最大的频率呢?一个区间最大的频率等于左区间最大频率,右区间最大频率,中点向两边拓展的长度,这三个值中最大的那个。这道题另外一个要点就是我们在询问中肯定要做很多次拓展,难道每次都要做O(n)的搜索吗?很明显不是,只要我们预处理出每个点向左向右最多能拓展的距离,以后每次拓展就可以用之前预处理的数据了。复杂度是O(1)。
代码如下:
#include <iostream>
#include <cstdlib>
#include <cstdio>
#define lson l, m, k << 1
#define rson m + 1, r, k << 1 | 1
using namespace std;
const int maxn = 100005;
int sum[maxn << 2], mark[maxn << 2], cnt[maxn], a[maxn];
int Left[maxn], Right[maxn];
void pushup(int k, int l, int r){//由子节点的信息来更新父节点的信息
sum[k] = max(sum[k << 1], sum[k << 1 | 1]);
int m = (l + r) >> 1;
int x = Left[m], y = Right[m], c;
if (x >= l && y <= r) c = y - x + 1;
else if (x >= l && y > r) c = r - x + 1;
else if (x < l && y <= r) c = y - l + 1;
else c = r - l + 1;
sum[k] = max(sum[k], c);
}
void build(int l, int r, int k){//递归建树
mark[k] = 0;
if (l == r){
sum[k] = 1;
return;
}
int m = (l + r) >> 1;
build(lson);
build(rson);
pushup(k, l, r);
}
int query(int l,int r, int k, int L, int R){
if (L <= l && R >= r){
return sum[k];
}
int m = (l + r) >> 1;
int res, lcnt = 0, rcnt = 0;
if (L <= m) lcnt = query(lson, L, R);
if (R > m) rcnt = query(rson, L, R);
res = max(lcnt, rcnt);
int c = 0;//如果所求区间横跨当前节点区间的中点,那么最后的答案就是
//左区间的值,右区间的值,中点向两边拓展的值这三个值中最大的那个
if (m >= L && m < R){
int x = Left[m], y = Right[m];
if (x >= L && y <= R) c = y - x + 1;
else if (x >= L && y > R) c = R - x + 1;
else if (x < L && y <= R) c = y - L + 1;
else c = R - L + 1;
}
res = max(res, c);
return res;
}
int main()
{
//freopen("1.txt", "r", stdin);
int n, q;
while (~scanf("%d%d", &n, &q) && n){
for (int i = 1; i <= n; i++)
scanf("%d", &a[i]);
for (int i = 1; i <= n; i++){//预处理出每个节点往左往右最多能拓展到哪里,保存在Left,Right中。
int j = i;
while (j >= 0 && a[j] == a[i])
j--;
Left[i] = j + 1;
j = i;
while (j <= n && a[j] == a[i])
j++;
Right[i] = j - 1;
}
build(1, n, 1);
int l, r;
while (q--){
scanf("%d%d", &l, &r);
printf("%d\n", query(1, n, 1, l, r));
}
}
return 0;
}