POJ 3368 RMQ--ST
e 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
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
先說一下題意 給出n個不減的數,詢問Q次,求這n個數中連續的相等的數的最大數量
思路:將全陣列轉化成兩個陣列xu[ ]代表著數字的順序-1 -1 1 1 1 1 3 10 10 10 就是
1 2 1 2 3 4 1 1 2 3
wei[ ]就是每一串相同字元的尾部index 2 2 6 6 6 6 7 10 10 10
還有一個 求區間 最大值的 RMQ
ans 如果要查詢的wei[l]和wei[r] 相等的話直接就是l-r+1
其他情況 左邊部分的l-r+1右邊部分的RMQ求最大值
#include<iostream>
#include<stdio.h>
using namespace std;
int num[100009];
int xu[100009];
int wei[100009];
int dp[100009][30];
int n,q;
void ST(int n)
{
for (int i = 1; i <= n; i++)
dp[i][0] = xu[i];
for (int j = 1; (1 << j) <= n; j++)
{
for (int i = 1; i + (1 << j) - 1 <= n; i++)
{
dp[i][j] = max(dp[i][j - 1], dp[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(dp[l][k], dp[r - (1 << k) + 1][k]);
}
int main()
{
while(cin>>n)
{
if(n==0)
break;
cin>>q;
for(int i=1; i<=n; i++)
{
scanf("%d",&num[i]);
}
xu[1]=1;
for(int i=2; i<=n; i++)
{
if(num[i]==num[i-1])
xu[i]=xu[i-1]+1;
else xu[i]=1;
}
wei[n]=n;
for(int i=n-1; i>0; i--)
{
if(num[i]==num[i+1])
wei[i]=wei[i+1];
else
wei[i]=i;
}
ST(n);
for(int i=0; i<q; i++)
{
int l,r;
scanf("%d%d",&l,&r);
if(wei[l]==wei[r])
printf("%d\n",xu[r]-xu[l]+1);
else
printf("%d\n",max(wei[l]-l+1,RMQ(wei[l]+1,r)));
}
}
return 0;
}