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;
}