Advertisement
pranavsindura

N logN DP

Mar 4th, 2021
824
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 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.     int B = 0;
  36.     set<pi> st[2]; // B -> even, B ^ 1 -> odd
  37.     vector<int> dp(n, inf);
  38.     for(int i = 0; i < n; i++)
  39.     {
  40.         if(A[i]) B ^= 1, st[B ^ 1].insert({(i ? dp[i - 1] : 0), i});
  41.         else st[B].insert({(i ? dp[i - 1] : 0), i});
  42.  
  43.         while(!st[B].empty() && st[B].begin()->ss < i - m + 1)
  44.             st[B].erase(st[B].begin());
  45.         while(!st[B ^ 1].empty() && st[B ^ 1].begin()->ss < i - m + 1)
  46.             st[B ^ 1].erase(st[B ^ 1].begin());
  47.  
  48.         if(!st[B ^ 1].empty())
  49.             dp[i] = min(dp[i], 1 + st[B ^ 1].begin()->ff);
  50.     }
  51.  
  52.     int ans = dp.back();
  53.     if(ans == inf) ans = -1;
  54.     cout << ans << endl;
  55. }
  56.  
  57. int main()
  58. {
  59.     FASTIO;
  60.     int t;
  61.     t = 1;
  62.     cin >> t;
  63.     while(t--)
  64.     {
  65.         cp();
  66.     }
  67.     return 0;
  68. }
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement