Educational Codeforces Round 5 (D. Longest k-Good Segment)(尺取法)

D. Longest k-Good Segment
time limit per test
1 second
memory limit per test
256 megabytes
input
standard input
output
standard output

The array a withn integers is given. Let's call the sequence of one or more consecutive elements inasegment. Also let's call the segmentk-good if it contains no more thank 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 usescanf/printf instead ofcin/cout in C++, prefer to useBufferedReader/PrintWriter instead ofScanner/System.out inJava.

Input

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

The second line contains n integersai (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 from1 ton from left to right.

Sample test(s)
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个数的最长连续子序列,输出起止位置

方法:尺取法,要注意这里的结束条件是cnt>k而不是cnt=k;

#include<stdio.h>
#include<string.h>
#include<map>
using namespace std; 
const int maxn=5e5+100;
int main()
  {int i,j,k,m,n;
   int l,r,l1,r1;
   int a[maxn];
   map<int,int> f;
   f.clear();
   scanf("%d %d",&n,&k);
   for(i=1;i<=n;i++)scanf("%d",a+i);
   l1=1; r1=1;
   l=1;r=1;
   int cnt=0;
   while(r<=n)
     {while(cnt<=k  &&r<=n)  //注意cnt>k时才能取出最长的包含k个值的序列,后面将多出来的那个数去掉
        {if(f[a[r]]==0)cnt++;
		 f[a[r]]++;	
		 r++;
		}
	  if(cnt>k)  //所选序列已经超出了k个,往前回溯一个
	    {f[a[r-1]]--;
		 r=r-1;
		 cnt--;	
	     }
      if(r-l>r1-l1){l1=l;r1=r;}
	  while(cnt==k)
	    {if(f[a[l]]==1)cnt--;
	    f[a[l]]--;
	    l++;	
		}
	 }	
	printf("%d %d",l1,r1-1); 
  }


你可能感兴趣的:(codeforces,尺取法)