UVa - 11235 - Frequent values(RMQ)

来源:互联网 发布:网络与新媒体职业规划 编辑:程序博客网 时间:2024/06/08 11:02

题意:输入一个n个元素的非减序列a[],接着进行q次询问,每次询问输入两个数L, R, 问a[L]与a[R]之间相同元素的个数最多有多少个。

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=2176

——>>RMQ, RMQ...游程编码,再用Sparse-Table即可,注意:查询时L与R位于同一段与相邻段的情况。

#include <iostream>#include <algorithm>#include <string.h>using namespace std;const int maxn = 100000 + 10;//a为输入的非减序列,value[i]为游程编码第i段的值,Count[i]为游程编码第i段的数的数量,num[i]为位置i所属段号, Left[i]为位置i所属段的左端位置,Right[i]为位置i所属段的右端位置,d为RMQ数组,cnt为总段数int a[maxn], value[maxn], Count[maxn], num[maxn], Left[maxn], Right[maxn], d[maxn][20], cnt;void init_RMQ()     //Sparse-Table算法{    int i, j;    for(i = 1; i <= cnt; i++) d[i][0] = Count[i];    for(j = 1; (1<<j) <= cnt; j++)        for(i = 1; i+(1<<j)-1 <= cnt; i++)            d[i][j] = max(d[i][j-1], d[i+(1<<(j-1))][j-1]);     //递推}int RMQ(int L, int R)       //查询最大值{    int k = 0;    while((1<<(k+1)) <= R-L+1) k++;     //找到最大整数k,使得2的k次方 <=  R-L+1    return max(d[L][k], d[R-(1<<k)+1][k]);}int main(){    int n, q, i, j, L, R, result;    while(cin>>n)    {        if(n == 0) return 0;        cin>>q;        for(i = 1; i <= n; i++) cin>>a[i];        memset(Count, 0, sizeof(Count));        value[1] = a[1];        //进行游程编码,先把第一个值赋上,后面的可以用下标-1-1-...        Count[1] = 1;        num[1] = 1;        Left[1] = 1;        Right[1] = 1;        j = 1;      //段号从1开始        for(i = 2; i <= n; i++)        {            if(a[i] != a[i-1])      //当与前一个数不一样的时候            {                j++;        //段数+1                value[j] = a[i];        //新段的值            }            Count[j]++;     //该段中元素个数+1            num[i] = j;     //该位置的元素所属段号        }        int k = 1, cur_left = 0, cur_right;     //以k为下标变量来给Left, Right数组赋值,cur_left为各段开始位置-1,cur_right为各段结尾位置        Count[0] = 0;        for(i = 1; i <= j; i++)     //游程编码共j段        {            cur_left += Count[i-1];     //cur_left为各段开始位置-1            cur_right = cur_left+Count[i];      //cur_right为各段结尾位置            for(; k <= cur_right; k++)            {                Left[k] = cur_left+1;                Right[k] = cur_right;            }        }        cnt = j;        init_RMQ();     //Sparse-Table        for(i = 0; i < q; i++)        {            cin>>L>>R;            result = max(Right[L]-L+1, R-Left[R]+1);        //三段比较得最大值:Right[L]-L+1,RMQ(num[L]+1, num[R]-1),R-Left[R]+1            if(num[L] == num[R])        //当两个位置在同一段时            {                cout<<R-L+1<<endl;            }            else if(num[L] + 1 == num[R])       //当两个位置所属段相邻时            {                cout<<result<<endl;            }            else        //当两个位置有隔段时            {                result = max(result, RMQ(num[L]+1, num[R]-1));                cout<<result<<endl;            }        }    }    return 0;}