每日一题之 hiho224 周 Split Array (暴力)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014046022/article/details/83052062

描述
You are given an sorted integer array A and an integer K. Can you split A into several sub-arrays that each sub-array has exactly K continuous increasing integers.

For example you can split {1, 1, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6} into {1, 2, 3}, {1, 2, 3}, {3, 4, 5}, {4, 5, 6}.

输入
The first line contains an integer T denoting the number of test cases. (1 <= T <= 5)

Each test case takes 2 lines. The first line contains an integer N denoting the size of array A and an integer K. (1 <= N <= 50000, 1 <= K <= N)

The second line contains N integers denoting array A. (1 <= Ai <= 100000)

输出
For each test case output YES or NO in a separate line.

样例输入
2
12 3
1 1 2 2 3 3 3 4 4 5 5 6
12 4
1 1 2 2 3 3 3 4 4 5 5 6
样例输出
YES
NO

题意:

给一个有N个元素的排好序的数组,现在要对这个数组进行切分,要求每块里面含k个连续的元素。如果能要求切分就输出YES,否则输出NO

思路:

暴力切分,用一个set存下所有元素,然后用一个数组存在该元素的数量,然后每次从set中取值,假设当前值为x,那么只要判断数组中下标为 ( x + 1 , x + 2 , &ThinSpace; , x + k 1 ) (x+1,x+2,\cdots,x+k-1) 存的值是大于0的,那就满足条件。并减少相应的计数,如果某个值计数为0,就从set中删除该值。

#include <cstdio>
#include <cstring>
#include <iostream>
#include <set>

using namespace std;

const int maxn = 1e5+5;

int A[5*maxn];

void solve(set<int>S, int num, int k) {

	set<int>::iterator it = S.begin();
	int i ;
	while(it != S.end()) {
		i = *it;
		for (int j = i+1; j <= i+k-1; ++j) {
			if (A[j] != 0 && A[j] >= A[i]) {
				A[j] -= A[i];
				if (A[j] == 0) S.erase(j);
			}
			else {
				cout << "NO" << endl;
				return;
			}

		}
		++it;
	}

	cout << "YES" << endl;

}

int main() {

	int t, n, k, x;
	cin >> t;
	while(t--) {
		cin >> n >> k;
		memset(A, 0, sizeof(A));
		int num = 0;
		set<int>S;
		for (int i = 0; i < n; ++i) {
			cin >> x;
			S.insert(x);
			++A[x];
		}

		solve(S, num, k);

	}

	return 0;
}

猜你喜欢

转载自blog.csdn.net/u014046022/article/details/83052062
今日推荐