UVa 11536 Smallest Sub-Array (水题, 滑动窗口)

题意:给定 n 个由0~m-1的整数组成的序列,输入 k ,问你找出连续的最短序列,使得这个序列含有1-k的所有整数。

析:这个题,很简单么,只要从头开始扫一遍就OK,时间复杂度为O(n)。

代码如下:

#include <cstdio>
#include <string>
#include <cstdlib>
#include <cmath>
#include <iostream>
#include <cstring>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
#include <cctype>
using namespace std ;
typedef long long LL;
typedef pair<int, int> P;
const int INF = 0x3f3f3f3f;
const double inf = 0x3f3f3f3f3f3f3f;
const double eps = 1e-8;
const int maxn = 1e6 + 5;
const int dr[] = {0, 0, -1, 1};
const int dc[] = {-1, 1, 0, 0};
int n, m;
inline bool is_in(int r, int c){
    return r >= 0 && r < n && c >= 0 && c < m;
}
int a[maxn];
int vis[1005];
void init(){
    a[0] = 1;  a[1] = 2; a[2] = 3;
    for(int i = 3 ; i < n; ++i)
        a[i] = (a[i-1]+a[i-2]+a[i-3]) % m + 1;
}

int main(){
    int T;  cin >> T;
    for(int kase = 1; kase <= T; ++kase){
        int k;
        scanf("%d %d %d", &n, &m, &k);
        init();
        int ans = INF;
        int s = 0, e = 0;
        memset(vis, 0, sizeof(vis));
        int cnt = 0;
        while(e < n){
            while(e < n && cnt < k){
                if(!vis[a[e]] && a[e] <= k)  ++cnt;
                ++vis[a[e]];
                ++e;
            }
            if(cnt == k)  ans = min(ans, e-s);
            --vis[a[s]];
            if(!vis[a[s]] && a[s] <= k)  --cnt;
            ++s;
        }
        printf("Case %d: ", kase);
        ans == INF ? printf("sequence nai
") : printf("%d
", ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/dwtfukgv/p/5724341.html