最长区间

D. Longest k-Good Segment
time limit per test1 second
memory limit per test256 megabytes
inputstandard input
outputstandard output
The array a with n integers is given. Let’s call the sequence of one or more consecutive elements in a segment. Also let’s call the segment k-good if it contains no more than k different values.

Find any longest k-good segment.

As the input/output can reach huge size it is recommended to use fast input/output methods: for example, prefer to use scanf/printf instead of cin/cout in C++, prefer to use BufferedReader/PrintWriter instead of Scanner/System.out in Java.

Input
The first line contains two integers n, k (1 ≤ k ≤ n ≤ 5·105) — the number of elements in a and the parameter k.

The second line contains n integers ai (0 ≤ ai ≤ 106) — the elements of the array a.

Output
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 a are numbered from 1 to n from left to right.

Examples
inputCopy
5 5
1 2 3 4 5
outputCopy
1 5
inputCopy
9 3
6 5 1 2 3 2 1 4 5
outputCopy
3 7

这题一开始对出现的次数想要用数组+循环但很费时,就无从下手。
此题思路就是:用循环让r增大,当r-l>k,再让l增加。每一次都对r,l和最大值比较,若大于最大值,最大值区间改为r,l
ac代码:
#include
#include
#include
#include
#include
#include
#include
#define ll long long
#define dep(i,a,b) for(int i=(a);i>=(b);i–)
#define rep(i,a,b) for(int i=(a);i<=(b);i++)
#define mes§ memset(p,0,sizeof§)
using namespace std;
int a[500005],b[1000005];
int main()
{
mes(b);
int l,r,p,q,count=0,k,n;
cin>>n>>k;
p=1;q=k,l=1,r=0;
rep(i,1,n)
scanf("%d",&a[i]);
while(r<n){
if(b[a[++r]]==0) count++;
b[a[r]]++;
while(count>k){
b[a[l]]–;
if(b[a[l]]==0) {
count–;}
l++;
}
if(r-l>q-p) {
q=r;
p=l;
}
}
cout<<p<<’ '<<q<<endl;
return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值