Smallest Sub-Array

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

思路:

贪心与动态规划。

核心就是函数solve()的方法:先找到能囊括1~K的最前区间,然后在左端进行试探,若少一个就补一个(cnt)。

注意进行初始以防出错。

#include<iostream>
#include<string.h>
using namespace std;
const int N=1e6+5;
int n,m,k,t;
int X[N],v[N];
int cnt,ans,a,b;
void init()
{
	memset(X,0,sizeof(X));
	memset(v,0,sizeof(v));//重置!
	X[1]=1,X[2]=2,X[3]=3;
	for(int i=4;i<=n;i++)
	{
		X[i]=(X[i-1]+X[i-2]+X[i-3])%m+1;
	}		
}
void solve()
{
	cnt=0,ans=N,a=1,b=1;
	while(true)
	{
		while(b<=n&&cnt<k)
		{
			v[X[b]]++;
			if(X[b]<=k&&v[X[b]]==1)
				cnt++;
			b++;
		}
		if(cnt<k)
			break;
		ans=min(b-a,ans);
		v[X[a]]--;
		if(X[a]<=k&&v[X[a]]==0)
			cnt--;
		a++;
	}
	if(ans==N)
		printf("sequence nai\n");
	else
		printf("%d\n",ans);
}
int main()
{
	scanf("%d",&t);
	n=0,m=0,k=0;
	int j=1;
	while(t--)
	{
		n=0,m=0,k=0;
		scanf("%d %d %d",&n,&m,&k);
		init();
		printf("Case %d: ",j);
		solve();
		j++;
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TherAndI

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值