Advertisement
asdfg0998

Untitled

Oct 24th, 2024
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <vector>
  3. using namespace std;
  4.  
  5. const int MOD = 1e9 + 7;
  6.  
  7. vector<int> calculatePrefixSums(const vector<int>& arr) {
  8.     int n = arr.size();
  9.     vector<int> prefixSums(n);
  10.     prefixSums[0] = arr[0];
  11.     for (int i = 1; i < n; ++i) {
  12.         prefixSums[i] = prefixSums[i - 1] + arr[i];
  13.     }
  14.     return prefixSums;
  15. }
  16.  
  17. int countValidPartitions(const vector<int>& arr) {
  18.     int n = arr.size();
  19.  
  20.     if (n == 0) return 0;
  21.    
  22.     vector<int> prefixSums = calculatePrefixSums(arr);
  23.    
  24.     vector<vector<int>> dp(n + 1, vector<int>(2, 0));
  25.    
  26.     dp[n][0] = dp[n][1] = 1;
  27.  
  28.     for (int i = n - 1; i >= 0; --i) {
  29.         int sum = 0;
  30.         for (int j = i; j < n; ++j) {
  31.             sum = prefixSums[j] - (i > 0 ? prefixSums[i - 1] : 0);
  32.             int currentSumParity = sum % 2;
  33.  
  34.             if (currentSumParity == 0) {
  35.                 dp[i][0] = (dp[i][0] + dp[j + 1][1]) % MOD;
  36.             } else {
  37.                 dp[i][1] = (dp[i][1] + dp[j + 1][0]) % MOD;
  38.             }
  39.         }
  40.     }
  41.     return (dp[0][0] + dp[0][1]) % MOD;
  42. }
  43.  
  44. int main() {
  45.     // Input example
  46.     int n = 4;
  47.     vector<int> arr = {1, 1, 1, 1};  // Example array
  48.  
  49.     cout << "Number of valid partitions (Optimized): " << countValidPartitions(arr) << endl;
  50.  
  51.     return 0;
  52. }
  53.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement