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.
Example
Input
5 5
1 2 3 4 5
Output
1 5
Input
9 3
6 5 1 2 3 2 1 4 5
Output
3 7
Input
3 1
1 2 3
Output
1 1
队内训练的时候没有想出来,只想到了一侧更新的方法,超时了
题解:
对于包含k不同个数字的连续序列可以采用尺取法的技巧进行更新;
有两个指针,头和尾,当其中的数字种类小于k时,就继续走;
当大于k时,就需要删除第一个数了,排除掉序列中的第一个数后,继续重复走,直至结束;
有一个技巧,对于每个数是否被访问的标记数组可以用来存它在当前的序列中存放的个数,这样删除时可以方便的判断它是否已经删除干净了,比如
4 5 5 4 1 1 2 3 4 3 3
当删除4时,每删除一个一个4,vis[4] 就 -1,这样当vis[4] == 0 s时就可以判断删除完了,就可以不用往后查看了;
#include<stdio.h>
#include<string.h>
#define maxn 1000010
int vis[maxn];
int a[maxn];
int main()
{
int n,k;
scanf("%d%d",&n,&k);
for(int i=0;i<n;i++)
scanf("%d",&a[i]);
memset(vis,0,sizeof(vis));
int x=0,y=0;
int px=0,py=0;
int cnt=0;
for(int i=0;i<n;i++)
{
if(vis[a[i]] == 0) cnt ++;
vis[a[i]]++;
py = i;
if(cnt > k)
{
while( px <= py )
{
vis[a[px]] --;
if( vis[ a[px] ] == 0)
{
cnt--;
px++;
break;
}
px++;
}
}
if(py-px>y-x)
{
x=px;
y=py;
}
}
printf("%d %d\n",x+1,y+1);
return 0;
}