【CodeForces - 616D 】Longest k-Good Segment (twopointer,尺取)
題干:
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
Input
5 5 1 2 3 4 5Output
1 5Input
9 3 6 5 1 2 3 2 1 4 5Output
3 7Input
3 1 1 2 3Output
1 1題目大意:
在長度為n的序列?中找出有不超過k個不同數字的最長連續子串,輸出子串開始以及結束的位置(若有多個答案,輸出任何?一個即可)
解題報告:
? ?尺取就好了。剛開始讀錯題了,讀成了恰有k個不同數字了。。不過還好if(now==k)改成if(now<=k)即可。
AC代碼:
//剛開始讀錯題了。。簡單尺取、、 #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #define ll long long using namespace std; int a[(int)5e5 + 5],cnt[(int)1e6 + 5]; int n,k,ans,ansl,ansr; int main() {cin>>n>>k;for(int i = 1; i<=n; i++) scanf("%d",a+i);int l = 1,r = 1,now = 0;while(r <= n) {if(cnt[a[r]] == 0) now++;cnt[a[r]]++;while(now > k) {cnt[a[l]]--;if(cnt[a[l]] == 0) now--;l++;}if(now <= k) {if(r-l+1 > ans) {ansl = l;ansr = r;ans = r-l+1;}}r++;}printf("%d %d\n",ansl,ansr);return 0 ;}?
總結
以上是生活随笔為你收集整理的【CodeForces - 616D 】Longest k-Good Segment (twopointer,尺取)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 小米12家族唯一一款直屏手机 小米12
- 下一篇: 重返恐龙时代!腾讯首款原生云游戏技术DE