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.
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.
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.
5 5
1 2 3 4 5
1 5
9 3
6 5 1 2 3 2 1 4 5
3 7
3 1
1 2 3
1 1
题意:第一行给你两个数m,k;
第二行给你n个数;
要求你找一个连续区间,这个区间不同的数的个数不超过k而且这个区间长度最大,输出区间端点l,r(任意一组就行)
分析:two pointers解决,知道这个方法做这个题简直就是水题,直接看代码。
#include<stdio.h> #include<string.h> #include<algorithm> using namespace std; int a[500010]; int vis[1000010]; int main() { int n,k; while(scanf("%d%d",&n,&k)==2) { for(int i=1;i<=n;i++) scanf("%d",&a[i]); memset(vis,0,sizeof(vis)); int len=1,l=1,r=1,sum=1;///len记录最长的长度,用来更新答案而已,l和r分别指向区间两端,sum表示的是a[l]到a[r]中不同的数的个数 int x=1,y=1; vis[a[1]]=1;///预处理第一个值 while(r<=n) { r++; if(r>n) break; if(vis[a[r]]==0)///加入这个值之前没有这个值,那么不同的数多了1,sum++ { sum++; vis[a[r]]++; } else vis[a[r]]++; while(sum>k) { vis[a[l]]--; if(!vis[a[l]]) sum--;///如果这个值-1后这个值就没有了,代表少了一个不同的数,sum-- l++; } if(r-l+1>len) { len=r-l+1; x=l,y=r; } } printf("%d %d\n",x,y); } return 0; }