专题测试三 贪心与动态规划 A - Smallest Sub-Array

  1. 题目
    Consider an integer sequence consisting of N elements where
    X1 = 1
    X2 = 2
    X3 = 3
    Xi = (Xi−1 + Xi−2 + Xi−3)%M + 1 for i = 4 to N
    Find 2 values a and b so that the sequence (Xa Xa+1 Xa+2 . . . Xb−1Xb) contains all the integers
    from [1, K]. If there are multiple solutions then make sure (b − a) is as low as possible.
    In other words, find the smallest subsequence from the given sequence that contains all the integers
    from 1 to K.
    Consider an example where N = 20, M = 12 and K = 4.
    The sequence is {1 2 3 7 1 12 9 11 9 6 3 7 5 4 5 3 1 10 3 3}.
    The smallest subsequence that contains all the integers {1 2 3 4} has length 13 and is highlighted
    in the following sequence:
    {1 2 3 7 1 12 9 11 9 6 3 7 5 4 5 3 1 10 3 3}.
    Input
    First line of input is an integer T (T < 100) that represents the number of test cases. Each case consists
    of a line containing 3 integers N (2 < N < 1000001), M (0 < M < 1001) and K (1 < K < 101). The
    meaning of these variables is mentioned above.
    Output
    For each case, output the case number followed by the minimum length of the subsequence. If there is
    no valid subsequence, output ‘sequence nai’ instead. Look at the sample for exact format.
    Sample Input
    2
    20 12 4
    20 12 8
    Sample Output
    Case 1: 13
    Case 2: sequence nai
  2. 思路
    尺取法,前面(右边)推进区间,找到满足条件区间之后后面(左边)收缩区间直到又不满足条件,记录最短的区间就可以了
  3. 代码
    #include<cstdio>
    #include<iostream>
    #include<string>
    #include<cstring>
    #include<algorithm>
    using namespace std;
    
    #define clear(a) memset(a,0,sizeof(a))
    
    const int maxx = 1000010;
    int t,n,m,k,q = 1,a[maxx],b[maxx];//b:统计数量
    
    int main()
    {
        scanf("%d",&t);
        while(t--)
    	{
            scanf("%d%d%d",&n,&m,&k);
    		clear(a);clear(b);
            a[1] = 1; a[2] = 2; a[3] = 3;
            for(int i=4;i<=n;i++)
                a[i] = (a[i-1] + a[i-2] + a[i-3]) % m + 1;
            int ans = maxx;
            int head = 0,tail = 1,c = 0;
            while(1)
    		{
                if(c == k)//缩尾
    			{
                    b[a[tail]] -- ;
                    if(b[a[tail]] == 0 && a[tail] <= k) c--;
                    tail++;
                    if(c == k) ans = min(ans, head - tail + 1);
                }
                else//伸头
    			{
                    head++;
                    if(head > n) break;
                    b[a[head]]++;
                    if(b[a[head]] == 1 && a[head] <= k) c++;//第一次进才加
                    if(c == k) ans = min(ans, head - tail + 1);
                }
            }
            printf("Case %d: ",q);
    		q++;
            if(ans != maxx) printf("%d\n",ans);
            else printf("sequence nai\n");
        }
        return 0;
    }
posted @ 2022-02-17 10:08  Benincasa  阅读(27)  评论(0)    收藏  举报