11536-smallest sub-array (sliding window)

Source: Internet
Author: User

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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.