fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <algorithm>
  4.  
  5. using namespace std;
  6.  
  7. void solve() {
  8. int n;
  9. cin >> n;
  10. vector<int> a(n);
  11. for (int i = 0; i < n; ++i) {
  12. cin >> a[i];
  13. }
  14.  
  15. // Tìm Median M của toàn bộ mảng
  16. vector<int> sorted_a = a;
  17. sort(sorted_a.begin(), sorted_a.end());
  18. int M = sorted_a[n / 2];
  19.  
  20. // Tạo mảng điều kiện biên
  21. vector<int> c1(n), c2(n);
  22. for (int i = 0; i < n; ++i) {
  23. c1[i] = (a[i] >= M) ? 1 : -1;
  24. c2[i] = (a[i] <= M) ? 1 : -1;
  25. }
  26.  
  27. // Khởi tạo mảng DP
  28. vector<int> dp(n + 1, -1);
  29. dp[0] = 0;
  30.  
  31. // Chuyển trạng thái DP O(N^2)
  32. for (int i = 1; i <= n; ++i) {
  33. int s1 = 0, s2 = 0;
  34. for (int j = i - 1; j >= 0; --j) {
  35. s1 += c1[j];
  36. s2 += c2[j];
  37.  
  38. // Nếu độ dài lẻ và trạng thái trước đó hợp lệ
  39. if ((i - j) % 2 == 1 && dp[j] != -1) {
  40. if (s1 > 0 && s2 > 0) {
  41. dp[i] = max(dp[i], dp[j] + 1);
  42. }
  43. }
  44. }
  45. }
  46.  
  47. cout << dp[n] << "\n";
  48. }
  49.  
  50. int main() {
  51. // Tối ưu I/O cho C++
  52. ios_base::sync_with_stdio(false);
  53. cin.tie(NULL);
  54.  
  55. int t;
  56. if (cin >> t) {
  57. while (t--) {
  58. solve();
  59. }
  60. }
  61. return 0;
  62. }
Success #stdin #stdout 0s 5320KB
stdin
10
5
3 3 2 4 3
7
9 5 7 7 4 7 7
9
1 1 1 1 1 1 1 1 1
1
5
3
1 2 3
3
2 2 2
5
1 2 3 4 5
5
2 1 3 2 2
7
2 2 1 2 3 2 2
9
2 1 2 3 2 1 2 3 2
stdout
3
3
9
1
1
3
1
3
5
5