Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define task "BITSTR"
- #include <iostream>
- #include <cstdio>
- #include <set>
- #include <algorithm>
- using namespace std;
- using ll = long long;
- using ld = long double;
- void read(int &x)
- {
- x = 0;
- register int c;
- while ((c = getchar()) && (c > '9' || c < '0'))
- ;
- for (; c >= '0' && c <= '9'; c = getchar())
- x = x * 10 + c - '0';
- }
- void readstr(string &s)
- {
- s.clear();
- register int c;
- while ((c = getchar()) && (c > '1' || c < '0'))
- ;
- for (; c >= '0' && c <= '1'; c = getchar())
- s.push_back(c);
- }
- constexpr int N = 2e5 + 5;
- constexpr int Inf = 1e9 + 7;
- int n, k, l[N], r[N], a[N], v[N], m(0);
- string s;
- #define bit(i, x) (((x) >> (i)) & 1)
- void Read()
- {
- cin >> n >> k >> s;
- s = " " + s;
- }
- void Sub_3()
- {
- for (int i = 1, j = 1; i <= n; ++i)
- {
- while (j <= n && s[i] == s[j])
- ++j;
- a[++m] = j - i;
- l[m] = r[m] = m;
- i = j - 1;
- }
- if (m <= k)
- {
- cout << 0;
- return;
- }
- if (k == 1)
- {
- cout << min(count(s.begin(), s.end(), '0'), count(s.begin(), s.end(), '1'));
- return;
- }
- int ans(Inf);
- for (int i = 0; i < 2; ++i)
- for (int j = 0; j < 2; ++j)
- {
- int res(0);
- if (i)
- res += a[1];
- if (j)
- res += a[m];
- struct com
- {
- bool operator()(const int &x, const int &y) const
- {
- return v[x] < v[y] || (v[x] == v[y] && x < y);
- }
- };
- set<int, com> q;
- for (int t = 2 + i; t <= m - 1 - j; ++t)
- {
- r[t] = t;
- l[t] = t;
- v[t] = a[t];
- q.insert(t);
- }
- int sz(q.size() + 2);
- while (sz > k)
- {
- int x = *q.begin();
- q.erase(q.begin());
- res += v[x];
- sz -= 2;
- if (q.find(l[x - 1]) == q.end())
- {
- auto v = q.find(r[x] + 1);
- if (v != q.end())
- q.erase(v);
- }
- else if (q.find(r[x] + 1) == q.end())
- q.erase(l[x - 1]);
- else
- {
- q.erase(l[x - 1]);
- q.erase(r[x] + 1);
- l[r[r[x] + 1]] = l[x - 1];
- r[l[x - 1]] = r[r[x] + 1];
- v[l[x - 1]] = v[l[x - 1]] + v[r[x] + 1] - v[x];
- q.insert(l[x - 1]);
- }
- }
- ans = min(ans, res);
- }
- cout << ans;
- }
- int32_t main()
- {
- ios::sync_with_stdio(0);
- cin.tie(0);
- cout.tie(0);
- if (fopen(task ".INP", "r"))
- {
- freopen(task ".INP", "r", stdin);
- freopen(task ".OUT", "w", stdout);
- }
- Read();
- Sub_3();
- }
Add Comment
Please, Sign In to add comment