The problem is actually a small deformation of the sliding window LRJ, except that the size of the window is variable. The specific method is similar to the example shuffle, with the first two pointers to maintain the window, with an array of CNT record 1~k each number in the window, with a variable C record the number of times in the window only one occurrence. So as long as C = = K This is a satisfying condition of the answer, take the smallest answer can be.
Because each element is only inserted and deleted once, the time complexity is O (n).
The algorithm also has a name called "Take the Ruler Method", which is characterized by the processing of an unknown length of continuous interval, by repeatedly pushing the beginning and end of the interval until the method of the answer.
See the code for details:
#include <bits/stdc++.h>using namespace Std;const int maxn = 1000000 + 10;int t,n,m,k,case = 0,a[maxn],cnt[maxn];map <int,int> p;vector<int> G[105];int Main () {scanf ("%d", &t); while (t--) {scanf ("%d%d%d", &n,&m,&k); memset (cnt,0,sizeof (CNT)); A[1] = 1; A[2] = 2; A[3] = 3; if (n>3) for (int i=4;i<=n;i++) {A[i] = (a[i-1]+a[i-2]+a[i-3])%m + 1; } int ans = 2000000000; int rear = 0,last = 1,c = 0; while (true) {if (c = = k) {Cnt[a[last]]--; if (cnt[a[last]] = = 0 && a[last] <= k) c--; last++; if (c = = k) ans = min (ans, rear-last + 1); } else {rear + +; if (Rear > N) break; cnt[a[rear]]++; if (cnt[a[rear]] = = 1 && a[rear] <= k) C + +; if (c = = k) ans = min (ans, rear-last + 1); } } printf ("Case%d:", ++case); if (ans! = 2000000000) printf ("%d\n", ans); else printf ("Sequence nai\n"); } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
11536-smallest sub-array (sliding window)