[bzoj3048][Usaco2013 Jan]Cow Lineup(离散+莫队)

本文详细介绍了一种称为“莫队算法”的数据处理方法,并通过一个具体的编程实例演示了其应用过程。文章首先介绍了莫队算法的基本概念及其应用场景,接着通过代码展示了如何使用C++实现该算法,并解释了其中的关键步骤,如lower_bound和upper_bound函数的应用。

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

题目:

我是超链接

题解:

哎呀看起来高大上的。。。。其实很简单啊,这个莫队也是伪
如果ta队列里的元素>k+1(就是不能靠删减直接取里面的最大值了)就head++;
这里认真介绍一下:

lower bound//大于等于a[i]的第一个位置
Returns an iterator pointing to the first element in the range [first,last) which does not compare less than val

upper bound//大于a[i]的第一个位置
Returns an iterator pointing to the first element in the range [first,last) which compares greater than val.

代码:

#include <cstdio>
#include <algorithm>
#include <iostream>
#include <cstring>
#define N 100005
using namespace std;
int a[N],b[N],c[N],q[N];
int main()
{
    int n,k,i;
    scanf("%d%d",&n,&k);
    for (i=1;i<=n;i++) scanf("%d",&a[i]),b[i]=a[i];

    sort(b+1,b+n+1);
    int cnt=unique(b+1,b+n+1)-b-1;//多少种不同的数字 
    for (int i=1;i<=n;i++)
      a[i]=lower_bound(b+1,b+n+1,a[i])-b;//大于等于a[i]的第一个位置 
    //离散

    int head=1,tail=0,kind=0,maxx=0;
    for (i=1;i<=n;i++)
    {
        if (c[a[i]]==0) kind++;
        while (kind>k+1) 
        {
            c[q[head]]--;
            if (!c[q[head]]) kind--;
            head++;
        }
        c[a[i]]++;maxx=max(maxx,c[a[i]]);
        q[++tail]=a[i];
    }
    printf("%d",maxx);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值