CF616D Longest k-Good Segment

题目描述

给定一个包含\(n\)个整数的序列\(a\)\(0\le a_i \le 10^6\),询问不重复数字个数\(\le k\)的最长区间的左右端点。如果有多解输出任意一组。

输入输出格式

输入格式:

The first line contains two integers \(n,k\) ( \(1 \leq k \leq n \leq 5·10^{5}\)) — the number of elements in \(a\) and the parameter \(k\) .

The second line contains nn integers \(a_{i}\)\(( 0<=a_{i}<=10^{6}\)) — the elements of the array \(a\) .

输出格式:

Print two integers \(l,r\) (\(1<=l<=r<=n\)) — the index of the left and the index of the right ends of some k-good longest segment. If there are several longest segments you can print any of them. The elements in aa are numbered from \(1\) to \(n\) from left to right.

输入输出样例

输入样例#1:

5 5
1 2 3 4 5

输出样例#1:

1 5

输入样例#2:

9 3
6 5 1 2 3 2 1 4 5

输出样例#2:

3 7

输入样例#3:

3 1
1 2 3

输出样例#3:

1 1

思路:题意为在长度为\(n\)的串中找出有k个不同数字的最长连续子串,输出子串开始以及结束的位置,然而数据有点水,我们直接用\(STL\)中的\(map\)记录一下即可。

代码:

#include<cstdio>
#include<algorithm>
#include<map>
#define maxn 1000007
using namespace std;
map <int,int> mp;
int a[maxn],l,len,cyh,zrj;
void del(int x)
{
    mp[x]--;
    if(mp[x]==0) mp.erase(x);
}
int main() {
  int n,k;
  scanf("%d%d",&n,&k);
  for(int i=0;i<n;++i) scanf("%d",&a[i]);
  for(int i=0;i<n;++i) {
    mp[a[i]]++;
    if(mp.size()>k) {
      for(;l<n&&mp.size()>k;++l)
        del(a[l]);
    }
    int ll=i-l+1;
    if(ll>len) {
      len=ll;
      cyh=l;
      zrj=i;
    }
  }
  printf("%d %d\n",cyh+1,zrj+1);
  return 0;
}
全部评论

相关推荐

2025-11-07 14:38
已编辑
东华理工大学 Java
糠茹频频影:寒假实习hc还是有的,继续投吧,至少1000+沟通以上
Java求职圈
点赞 评论 收藏
分享
脑袋锈住了:你这算啥,哥们中科院中强所硕士,本科211,叫我去干分拣,时薪20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务