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-12-15 19:41
已编辑
广东工业大学 前端工程师
smile丶snow:尽量保证的一张a4纸吧。为什么工作经历只有公司?如果项目经历是工作里面的,应该写到工作经历里的吧。没有写项目职责,项目全是一个人写的吗?标题大小也好怪。两个项目的分割看不出来是,它和那些项目成功字体是一样大的
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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