【AtCoder】C - Colorful Candies map+双指针
作者:互联网
先看一则map的运用:
#include<bits/stdc++.h>
using namespace std;
map<int,int>mp;
int main()
{
mp[1]=2;
mp[2]=3;
cout<<mp.size()<<endl;
mp[1]=0;
cout<<mp.size()<<endl;
mp.erase(1);
cout<<mp.size()<<endl;
return 0;
}
/*输出
2
2
1
*/
善用map的删除功能。然后就可以做这道题了。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
#define pb push_back
#define fi first
#define se second
#define mem(a,x) memset(a,x,sizeof(a));
#define db double
#define fir(i,a,n) for(int i=a;i<=n;i++)
//======================
const int N=3e5+10;
int a[N],b[N];//b[i] 以i为结尾的
map<int,int>mp;
int ans=-1;
int n,k;
int main()
{
cin>>n>>k;
for(int i=1;i<=n;i++) cin>>a[i];
for(int i=1;i<=k;i++)
{
mp[a[i]]++;
}
b[k]=mp.size();
for(int i=k+1;i<=n;i++)
{
//1~k 2~k+1 到k+1即加k+1 减1(i-k)
mp[a[i]]++;
mp[a[i-k]]--;
if(mp[a[i-k]]<=0)
{
mp.erase(a[i-k]);
}
b[i]=mp.size();
}
fir(i,k,n)
{
ans=max(ans,b[i]);
}
cout<<ans;
return 0;
}
标签:AtCoder,Colorful,map,Candies,long,int,mp,ans,define 来源: https://blog.csdn.net/karshey/article/details/120743045