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;
}