每日一題之 hiho224 周 Split Array (暴力)
描述
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,那麼只要判斷陣列中下標為 存的值是大於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;
}