C - Colorful Candies AtCoder Beginner Contest 210

这篇博客介绍了AtCoder Beginner Contest 210中的一道题目,目标是找到Takahashi能获得的最大不同颜色糖果数。问题涉及滑动窗口和颜色计数策略,通过优化选择区间来最大化糖果颜色的多样性。

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

https://atcoder.jp/contests/abc210/tasks/abc210_c

题目描述:

There are N candies arranged in a row from left to right. Each of these candies has one color that is one of the 10^9 colors called Color 1, Color 2, ……, and Color 10^9. For each i=1,2,…,N, the color of the ii-th candy from the left is Color ci.

From this row, Takahashi can choose K consecutive candies and get them. That is, he can choose an integer ii such that 1≤i≤N−K+1 and get the i-th, (i+1)-th, (i+2)-th, ……, (i+K−1)-th candy from the left.

Takahashi likes to eat colorful candies, so the more variety of colors his candies have, the happier he will be. Print the maximum possible number of distinct colors in candies he gets.

数据范围:

  • 1≤K≤N≤3×10^5

  • 1≤ci≤10^9

  • All values in input are integers.

输入:

Input is given from Standard Input in the following format:

N K
c1 c2 …… cN

输出:

Print the maximum possible number of distinct colors in candies Takahashi gets.

样例输入1

7 3
1 2 1 2 3 3 1

样例输出1

3

If Takahashi gets the 33-rd through 55-th candies, they will have 33 distinct colors, which is the maximum possible number.

样例输入2

5 5
4 4 4 4 4

样例输出2

1

Takahashi can get all of these candies, but they are in a single color.

样例输入3

10 6
304621362 506696497 304621362 506696497 834022578 304621362 414720753 304621362 304621362 414720753

样例输出3

4

思路:

可以将选定的区间 [i-k+1,i] 看做一个滑动模块,计算模块内的糖果种类数量。

利用map存数据,当滑动至下一个位置后,某一类的糖果数量为0,则删除该糖果,防止重复计算。

代码:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <map>
using namespace std;
typedef long long ll;
const int N = 3e5+5;
ll c[N];
​
int main()
{
    ios::sync_with_stdio(false);
    int k,n;
    cin>>n>>k;
    int res = 0;    //res记录糖果种类 
    for(int i=0;i<n;i++) cin>>c[i];
    map<int,int> mp; 
    for(int i=0;i<n;i++){
        mp[c[i]] += 1;  //c[i]类的糖果++ 
        if(i >= k-1){
            if(res < mp.size()) res = mp.size();        //更新res的值,mp.size()计算区间[i-k+1,i]内糖果数 
            mp[c[i-k+1]] -= 1;                          //前一个糖果数-- 
            if(mp[c[i-k+1]] == 0) mp.erase(c[i-k+1]);   //当该种类数量为0时,删除该种类的糖果            
        }
    }
    cout<<res;
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值