POJ1989总结

The Cow Lineup

题目来源

Description

Farmer John’s N cows (1 <= N <= 100,000) are lined up in a row.Each cow is labeled with a number in the range 1…K (1 <= K <=10,000) identifying her breed. For example, a line of 14 cows might have these breeds:

    1 5 3 2 5 1 3 4 4 2 5 1 2 3

Farmer John’s acute mathematical mind notices all sorts of properties of number sequences like that above. For instance, he notices that the sequence 3 4 1 3 is a subsequence (not necessarily contiguous) of the sequence of breed IDs above. FJ is curious what is the length of the shortest possible sequence he can construct out of numbers in the range 1..K that is NOT a subsequence of the breed IDs of his cows. Help him solve this problem.

Input

* Line 1: Two integers, N and K

* Lines 2..N+1: Each line contains a single integer that is the breed ID of a cow. Line 2 describes cow 1; line 3 describes cow 2; and so on.

Output

* Line 1: The length of the shortest sequence that is not a subsequence of the input

Sample Input

14 5
1
5
3
2
5
1
3
4
4
2
5
1
2
3

Sample Output

3

Hint

All the single digit ‘sequences’ appear. Each of the 25 two digit sequences also appears. Of the three digit sequences, the sequence 2, 2, 4 does not appear.

我的代码

要想求最短的非子序列长度,即要求最长的子序列长度。可以将整个序列分成若干段,除了最后一段,每一段满足1..k每一个数至少出现一次,那么有多少这样的段,就能表示多长的子序列的全排列。这样问题就变成遍历一遍序列求最多有多少个这样的子段的问题。

#include<stdio.h>
#include<string.h>
int main()
{
	int n,k,ans=1,hit=0;
	int cows[100010];
	int flag[10010];
	scanf("%d%d",&n,&k);
	for (int i=0;i<n;i++) scanf("%d",&cows[i]);
	for (int i=0;i<n;i++)
	{
		if (flag[cows[i]]==0)
		{
			hit++;
			flag[cows[i]]=1;
		}
		if (hit%k==0) 
		{
			memset(flag,0,sizeof(flag));
			hit=0;
			ans++;
		}
	}
	printf("%d\n",ans);
	return 0;
}

发表评论