Dang_Quan_10_Tin

DHBB112021_BITSTR (NguyenHoangVu)

Aug 15th, 2021
1,258
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.15 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 200005;
  6.  
  7. int l[N], r[N], v[N];
  8.  
  9. struct compare {
  10.     bool operator () (int i, int j) const {
  11.         return v[i] < v[j] ||(v[i] == v[j] && i < j);
  12.     }
  13. };
  14.  
  15. int main() {
  16.     freopen("bitstr.inp", "r", stdin);
  17.     freopen("bitstr.out", "w", stdout);
  18.     cin.tie(0)->sync_with_stdio(0);
  19.     int n, k; string s;
  20.     cin >> n >> k >> s;
  21.     vector<int> a;
  22.     int res = n;
  23.     for (int i = 0; i < n; ) {
  24.         int j = i;
  25.         while (j < n && s[i] == s[j]) j++;
  26.         a.push_back(j - i); i = j;
  27.     }
  28.     n = a.size();
  29.     if (a.size() < 4) {
  30.         for (int m = 0; m < (1 << n); m++) {
  31.             int cnt = 0, cur = 0;
  32.             for (int i = 0; i < n; i++) {
  33.                 if (m >> i & 1) cur += a[i];
  34.                 if (i && (m >> i & 1) ==
  35.                 (m >> (i - 1) & 1)) cnt++;
  36.             }
  37.             if (cnt + 1 <= k)
  38.                 res = min(res, cur);
  39.         }
  40.         return cout << res, 0;
  41.     }
  42.  
  43.     set<int, compare> seg;
  44.     for (int cl = 1; cl <= 2; cl++)
  45.         for (int cr = 1; cr <= 2; cr++) {
  46.             seg.clear();
  47.             for (int i = cl; i + cr < n; i++) {
  48.                 l[i] = r[i] = i; v[i] = a[i];
  49.                 seg.insert(i);
  50.             }
  51.             int cur = 0, num = seg.size() + 2;
  52.             if (cl > 1) cur += a[0];
  53.             if (cr > 1) cur += a.back();
  54.             while (num > k && seg.size()) {
  55.                 int x = *seg.begin(); seg.erase(x);
  56.                 int y = r[x]; cur += v[x]; num -= 2;
  57.                 if (x == 0 || !seg.count(l[x - 1]))
  58.                     seg.erase(y + 1);
  59.                 else if (!seg.count(y + 1))
  60.                     seg.erase(l[x - 1]);
  61.                 else {
  62.                     seg.erase(y + 1);
  63.                     v[x] -= v[y + 1];
  64.                     seg.erase(l[x - 1]);
  65.                     v[l[x - 1]] -= v[x];
  66.                     r[l[x - 1]] = r[y + 1];
  67.                     l[r[y + 1]] = l[x - 1];
  68.                     seg.insert(l[x - 1]);
  69.                 }
  70.             }
  71.             if (num <= k) res = min(res, cur);
  72.         }
  73.     cout << res;
  74. }
  75.  
Advertisement
Add Comment
Please, Sign In to add comment