跳到正文

题解

题解:B4098 [CSP-X2022 山东] 动物园

Leaf_c17约 2 分钟
原文

这是 2025年11月12日 存档的第 1 版,不是当前版本。查看当前版本

文章信息与版本

文章信息

发布
2025年5月5日
收录
2025年12月12日
更新
2026年11月13日
篇幅
约 2 分钟
题目
B4098

版本

  1. v2当前
  2. v1

1.思路

设小明要从第 l 个场馆到第 r 个场馆,且当前有 sum 个不同的动物。对于每一个状态,我们可以分成 2 类:

1.sum<m:r++ 扩大序列的长度 更新sum

2.sum==m 更新答案 l++ 缩小序列的长度 更新sum

2.CODE(100pts)

C++
#include<bits/stdc++.h>
#define ll long long
using namespace std;
//====================
const int N=1e6+10;
//====================
const int INF=0x3f3f3f3f;
//====================
long long n, m,l=1,r;
long long c[N],cnt[N],sum=0;
long long minn=INF;
//====================
//====================
void Solve(void){
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        cin>>c[i];
    }//cnt[c[1]]=1;
    while(r<=n){
        if(sum<m){
        	r++;
            if(cnt[c[r]]==0)sum++,cnt[c[r]]++;
            else cnt[c[r]]++;
        }else{
        	minn=min(minn,r-l+1);
            cnt[c[l]]--;
            if(cnt[c[l]]==0)sum--;
            l++;
        }
        
    }cout<<minn*10;
}
//====================
//====================
int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);cout.tie(NULL);
    ll T=1;//cin>>T;
	while(T--)Solve(); 
    return 0;
}