UVa 11536 Smallest Sub-Array

本文介绍了一个寻找特定整数序列中包含指定整数集合的最小子序列的问题,并提供了一段C++代码实现。该问题要求从给定序列中找到长度最短的子序列,该子序列需包含所有1到K之间的整数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

11536 - Smallest Sub-Array

Time limit: 8.000 seconds

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



#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
const int maxn=1000005;
const int N=105;

int a[maxn]= {0,1,2,3},b[N],pre[maxn],n,m,k;
queue <int> q;

void initial()
{
    memset(b,0,sizeof(b));
    memset(pre,0,sizeof(pre));
    while(!q.empty())  q.pop();
}

void input()
{
    scanf("%d %d %d",&n,&m,&k);
    for(int i=4; i<=n; i++)  a[i]=(a[i-1]+a[i-2]+a[i-3])%m+1;
}

void solve(int co)
{
    int cnt=0,ans=maxn,Max=-1;
    for(int i=1; i<=n; i++)
    {
        while(cnt==k)
        {
            int t=q.front();
            ans=min(ans,Max+1-t);
            b[pre[t]]--;
            if(b[pre[t]]==0)  cnt--;
            q.pop();
        }
        if(a[i]<=k && a[i]>=1)
        {
            if(!b[a[i]])  cnt++;
            b[a[i]]++;
            pre[i]=a[i];
            q.push(i);
            Max=max(i,Max);
        }
    }
    if(ans!=maxn)  printf("Case %d: %d\n",co,ans);
    else  printf("Case %d: sequence nai\n",co);
}

int main()
{
    int T;
    scanf("%d",&T);
    for(int co=1; co<=T; co++)
    {
        initial();
        input();
        solve(co);
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值