【刷题】梦里的难题

Description

······

分析:

我们可以把这么一个序列分成n段,每段均含有数字1-k,这样,这么多段里面一定有长度为n的所有子序列。

如:

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

可以看出分成了两段,答案为段数+1即3。

这个当1和2均有时,马上开始下一段,以求最优值。可以说,这是一种贪心。

1 2 | 2 1 | 1 1 2 | 2 2 1 | 1 2 | 2 2 1 | 1 2 | 2 1 | 1 2 | 1 2 | 1

Code:

#include <iostream>
#include <cstring>

#define SIZE 15000

using namespace std;

bool a[SIZE];

int main(int argc, char** argv)
{
	int n, i, temp, res = 1, x, k; // 刚开始一个都没有,最短找不到的序列长度为1
	
	cin >> n >> k;
	temp = k;
	for (i = 1; i <= n; i++)
	{
		cin >> x;
		if (!a[x])
		{
			a[x] = true;
			temp--; // 从1到k中又有了一个数
			if (!temp)
			{
				res++; // 新分段
				temp = k;
				memset(a, 0, sizeof (a)); // 重置
			}
		}
	}
	
	cout << res << endl;
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/drtlstf/article/details/80779030