Frequent values(ST)

本文介绍了一种解决区间内最频繁数值查询问题的有效算法。通过预处理数组来记录每个值出现的累积次数,并使用ST表进行区间最大值的快速查询,以应对大规模数据集上的多次查询需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

描述

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.

输入

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 nintegers 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.

输出

For each query, print one line with one integer: The number of occurrences of the most frequent value within the given range.

样例输入

10 3
-1 -1 1 1 1 1 3 10 10 10
2 3
1 10
5 10
0

样例输出

1
4
3

提示

A naive algorithm may not run in time!
题目大意:
给定一个序列,若干个查询,查询区间内出现最频繁的数的个数。
先预处理当前位置的值前面和它相同的个数,例如样例转化为1,2,1,2,3,4,1,1,2,3。然后ST预处理区间最大值,单纯的查询最大值会出现问题,例如[4,7]ST表得出的答案为4,所以可以将我们要查询的左端点更新一下,更新到一个新的1的位置,这样就不会出现那种问题了。
#include <bits/stdc++.h>
using namespace std;
const int INF=0x3f3f3f3f;
const int N=1e5+5;
int n,m,a[N],rt[N],pre[N];
int st[N][20];
int query(int l,int r)
{
    if(l>r) return 0;
    int k=log2(r-l+1);
    return max(st[l][k],st[r-(1<<k)+1][k]);
}
int main()
{
    while(~scanf("%d",&n),n)
    {
        memset(st,0,sizeof st);
        scanf("%d",&m);
        a[0]=INF;
        for(int i=1;i<=n;i++)
            scanf("%d",&a[i]);
        for(int i=1;i<=n;i++)
        {
            if(a[i]==a[i-1]) pre[i]=pre[i-1]+1;
            else pre[i]=1;
        }
        for(int i=1;i<=n;i++)
            st[i][0]=pre[i];
        for(int j=1;j<20;j++)
            for(int i=1;i+(1<<(j-1))<=n;i++)
                st[i][j]=max(st[i][j-1],st[i+(1<<(j-1))][j-1]);
        rt[n]=n;
        for(int i=n-1;i>=1;i--)
        {
            if(a[i]==a[i+1]) rt[i]=rt[i+1];
            else rt[i]=i;
        }
        while(m--)
        {
            int l,r,tmp;
            scanf("%d%d",&l,&r);
            if(rt[l]==rt[l-1])  tmp=min(r,rt[l])+1;
            else tmp=l;
            int ans=query(tmp,r);
            ans=max(ans,tmp-l);
            printf("%d\n",ans);
        }
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/zdragon1104/p/9499683.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值