Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 15134 | Accepted: 5519 |
Description
You are given a sequence of n integers a1 , a2 , ... , an in non-decreasing order. In addition to that, you are given several queries consisting of indices i and j (1 ≤ i ≤ j ≤ n). For each query, determine the most frequent value among the integers ai , ... , aj.
Input
The input consists of several test cases. Each test case starts with a line containing two integers n and q (1 ≤ n, q ≤ 100000). The next line contains n integers a1 , ... , an (-100000 ≤ ai ≤ 100000, for each i ∈ {1, ..., n}) separated by spaces. You can assume that for each i ∈ {1, ..., n-1}: ai ≤ ai+1. The following q lines contain one query each, consisting of two integers i and j (1 ≤ i ≤ j ≤ n), which indicate the boundary indices for the
query.
The last test case is followed by a line containing a single 0.
Output
For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.
Sample Input
10 3 -1 -1 1 1 1 1 3 10 10 10 2 3 1 10 5 10 0
Sample Output
1 4 3
Source
题意:给出一个长度为n的不下降序列,然后m次查询,每次输入两个数l,r,输出区间[l,r]中连续的数中最长的数目是多少。
思路:将输入的不下降序列进行预处理,找出其中的相邻的数字的相邻的数目,存储在p数组中,然后作为RMQ算法中dp的初值,每次输入l,r时,输出该区间的最大值就可以了。
ps:不过之中有一个需要注意的地方,就是每次询问[l,r]时,要先将这个区间分成两个部分,前半部分求出与num[pt] == num[l]的个数,直到num[pt]!=num[l],当然pt<=r然后对[pt,r]进行RMQ求解,这样做的原因是排除在l之前还有数与num[l]相等。这样的话可能会影响结果。然后将RMQ求解得到的结果与pt-l的值进行取最大值就可以了。
#include<iostream>
#include<algorithm>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
using namespace std;
const int N = 200010;
int maxx[N][20];
int num[N];
int p[N];
int n,m;
void play() {
int l = floor(log10(double(n))/log10(double(2)));
for(int j=1; j<=l; j++) {
for(int i=1; i<=n+1-(1<<j); i++) {
maxx[i][j] = max(maxx[i][j-1],maxx[i+(1<<(j-1))][j-1]);
}
}
}
int RMQ(int xx,int yy) {
if(xx>yy) {
return 0;
}
int pp = floor(log10(double(yy-xx))/log10(double(2)));
return max(maxx[xx][pp],maxx[yy-(1<<pp)+1][pp]);
}
int main() {
while(scanf("%d",&n)!=EOF) {
if(n == 0) {
break;
}
scanf("%d",&m);
for(int i=1; i<=n; i++) {
scanf("%d",&num[i]);
if(i == 1) {
p[i] = 1;
} else {
if(num[i] == num[i-1]) {
p[i] = p[i-1] + 1;
} else {
p[i] = 1;
}
}
}
for(int i=1; i<=n; i++) {
maxx[i][0] = p[i];
}
play();
int x,y;
while(m--) {
scanf("%d%d",&x,&y);
int pt = x;
while(pt<=y && num[pt] == num[pt-1]) {
pt++;
}
int ans = RMQ(pt,y);
ans = max(ans,pt-x);
printf("%d\n",ans);
}
}
return 0;
}