题目链接:【codeforces 616D】
在长度为n的串中找出有k个不同数字的最长连续子串,输出子串开始以及结束的位置
map的简单应用
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <string>
#include <map>
using namespace std;
const int inf=5*1e5+10;
int p[inf];
map<int, int>mp;
int main()
{
mp.clear();
int n, k, len=-1, l, r;
scanf("%d%d", &n, &k);
for(int i=1; i<=n; i++)
{
scanf("%d", &p[i]);
}
mp[p[1]]++;
l=r=1;
int li=1, ri=1;
for(int i=2; i<=n; i++)
{
mp[p[i]]++;
int ss = mp.size();
if(ss==k+1)
{
int ans = ri-li+1;
if(ans>len)
{
len = ans;
l=li, r=ri;
}
while(ss>k)
{
mp[p[li]]--;
if(mp[p[li]]==0) mp.erase(p[li]);
li++;
ss = mp.size();
}
}
ri=i;
}
int ans = ri-li+1;
if(ans>len)
{
l=li, r=ri;
}
printf("%d %d\n", l, r);
return 0;
}