11536 - Smallest Sub-Array (two pointer)


H

Smallest Sub-Array

Input: Standard Input

Output: Standard Output

 

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-1 Xb) 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 “sequencenai” instead. Look at the sample for exact format.

 

Sample Input                               Output for Sample Input

2

20 12 4

20 12 8

Case 1: 13

Case 2: sequence nai


题意:根据题目公式构造出序列,找出一个最短子序列包含1-k的数字,输出长度

思路:先构造出序列。然后利用two pointer的思想去处理。

代码:

#include <stdio.h>
#include <string.h>
#define min(a,b) ((a)<(b)?(a):(b))
const int N = 1000005;
int t, n, m, k, x[N], v[105];

bool init() {
	scanf("%d%d%d", &n, &m, &k);
	int num = 3;
	memset(v, 0, sizeof(v));
	x[0] = N; x[1] = 1; x[2] = 2; x[3] = 3;
	v[1] = v[2] = v[3] = 1;
	for (int i = 4; i <= n; i++) {
		x[i] = (x[i - 1] + x[i - 2] + x[i - 3]) % m + 1;
		if (x[i] <= k && !v[x[i]]) {
			v[x[i]] = 1;
			num++;
		}
	}
	if (num < k) return false;
	return true;
}

int solve() {
	int ans = N;
	int l = 0, num = 0;
	memset(v, 0, sizeof(v));
	for (int r = 1; r <= n; r++) {
		if (x[r] <= k) {
			if (!v[x[r]]) num++;
			v[x[r]] = r;
		}
		if (num == k) {
			ans = min(ans, r - l);
			while(1) {
				if (x[l] <= k && v[x[l]] == l) {
					v[x[l]] = 0;
					num--;
					break;
				}
				ans = min(ans, r - l);
				l++;
			}
		}
	}
	return ans;
}

int main() {
	int cas = 0;
	scanf("%d", &t);
	while (t--) {
		printf("Case %d: ", ++cas);
		if (init()) printf("%d\n", solve());
		else printf("sequence nai\n");
	}
	return 0;
}



11536 - Smallest Sub-Array (two pointer)

上一篇:POJ 2406 kmp简单应用


下一篇:UVa10599 Robots(II)