Advertisement
pranavsindura

N^2 DP

Mar 4th, 2021
782
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.42 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. #define all(x)    x.begin(), x.end()
  3. #define allr(x)   x.rbegin(), x.rend()
  4. #define sz(x)     ((int)x.size())
  5. #define ln(x)     ((int)x.length())
  6. #define mp        make_pair
  7. #define pb        push_back
  8. #define ff        first
  9. #define ss        second
  10. #define endl      '\n'
  11. #define dbg(x)    cout << #x << ": " << x << endl;
  12. #define clr(x,v)  memset(x, v, sizeof(x));
  13. #define fix(x)    cout << setprecision(x) << fixed;
  14. #define FASTIO    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
  15. using namespace std;
  16.  
  17. using ll = long long int;
  18. using ld = long double;
  19. using pi = pair<int, int>;
  20.  
  21. const double PI = acos(-1.0);
  22. const double eps = 1e-9;
  23. const ll mod = 1e9 + 7;
  24. const int inf = 1e7;
  25. const int MAXN = 1e5 + 5;
  26.  
  27. void cp()
  28. {
  29.     int n, m;
  30.     cin >> n >> m;
  31.     vector<int> A(n);
  32.     for(int &x : A)
  33.         cin >> x;
  34.  
  35.     partial_sum(all(A), A.begin());
  36.  
  37.     auto sum = [&](int x, int y)
  38.     {
  39.         return A[y] - (x ? A[x - 1] : 0);
  40.     };
  41.  
  42.     vector<int> dp(n, inf);
  43.     for(int i = 0; i < n; i++)
  44.         for(int j = max(0, i - m + 1); j <= i; j++)
  45.             if(sum(j, i) % 2)
  46.                 dp[i] = min(dp[i], 1 + (j ? dp[j - 1] : 0));
  47.  
  48.     int ans = dp.back();
  49.     if(ans == inf) ans = -1;
  50.     cout << ans << endl;
  51. }
  52.  
  53. int main()
  54. {
  55.     FASTIO;
  56.     int t;
  57.     t = 1;
  58.     cin >> t;
  59.     while(t--)
  60.     {
  61.         cp();
  62.     }
  63.     return 0;
  64. }
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement