CF616D Longest k-Good Segment

本文介绍了一种使用STL map数据结构解决寻找长度为n的序列中,含有k个不同数字的最长子串的问题。通过实时更新map记录元素出现次数,实现高效查找并输出子串起始和结束位置。

题目描述

给定一个包含\(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;
}

转载于:https://www.cnblogs.com/grcyh/p/10201435.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值