题意:给出非降序的n个数字的序列(有重复),然后给出i,j问[i,j]范围内出现最多次数的值的次数。
题解:经典的RMQ问题,按书上题解的思路,先把序列分段,即相同数字是一个段,用val[cnt]和count[cnt]表示第cnt段的值和出现次数,num[i],l[i],r[i]分别表示位置i所在段编号(cnt),左右端点位置,那么每次查询[i,j]时,就是要计算i到i左端点的元素个数,j到j右端点的元素个数,还有num[i] + 1到num[j] - 1段的count的最大值,这三者中的最大值。还有就是如果i,j在同一段结果就是j - i +
1。方法原样调用RMQ的预处理函数和查询函数。
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; const int N = 100005; int n, q, cnt; int Count[N], val[N], l[N], r[N], num[N], f[N][20]; void RMQ_init() { for (int i = 0; i < cnt; i++) f[i][0] = Count[i]; for (int j = 1; (1 << j) <= cnt; j++) for (int i = 0; i + (1 << j) - 1 < cnt; i++) f[i][j] = max(f[i][j - 1], f[i + (1 << (j - 1))][j - 1]); } int RMQ(int L, int R) { int k = 0; while (1 << (k + 1) <= R - L + 1) k++; return max(f[L][k], f[R - (1 << k) + 1][k]); } int main() { while (scanf("%d", &n) && n) { memset(Count, 0, sizeof(Count)); memset(f, 0, sizeof(f)); scanf("%d", &q); cnt = 0; scanf("%d", &val[cnt]); Count[cnt]++; num[0] = l[0] = r[0] = 0; int a, b, ll = 0; for (int i = 1; i < n; i++) { scanf("%d", &a); if (a == val[cnt]) { Count[cnt]++; l[i] = ll; } else { for (int j = ll, k = 0; k < Count[cnt]; k++, j++) r[j] = i - 1; l[i] = i; ll = i; cnt++; val[cnt] = a; Count[cnt]++; } num[i] = cnt; } RMQ_init(); while (q--) { scanf("%d%d", &a, &b); a--; b--; if (num[a] == num[b]) printf("%d\n", b - a + 1); else { int res = max(r[a] - a + 1, b - l[b] + 1); if (num[b] - num[a] == 1) printf("%d\n", res); else printf("%d\n", max(res, RMQ(num[a] + 1, num[b] - 1))); } } } return 0; }
原文地址:http://blog.csdn.net/hyczms/article/details/44875219