-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBeautiful Flip
83 lines (81 loc) Β· 1.91 KB
/
Beautiful Flip
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define FOR(i , a , b) for(int i = (a);i <= (b);i++)
#define FOD(i , a , b) for(int i = (a);i >= (b);i--)
#define REP(i , n) for(int i = 1;i <= (n);i++)
#define REP0(i , n) for(int i = 0;i < (n);i++)
#define pb push_back
#define printclock cerr<<"\nTime : "<<1000*(double)clock()/(double)CLOCKS_PER_SEC<<"ms\n";
const int mod = 1e9 + 7,inf = 1000111000, mxn = 5e5 + 5;
int n, k, p[mxn];
string s;
inline void maxz(int &a, int b)
{
if(a < b) a = b;
}
void solve()
{
cin >> n >> k >> s;
s = ' ' + s;
int cnt0 = 0 , cnt1 = 0;
FOR(i, 1, n)
{
int x = (s[i] == '1') ? 1 : -1;
p[i] = p[i - 1] + x;
// cout << p[i] << ' ';
if(s[i] == '1') cnt1++;
else cnt0++;
}
// cout << '\n';
int all = p[n];
multiset<int> s;
s.insert(2 * p[0]);
int ans = 0;
ans = max(ans , min(cnt0 , cnt1));
FOR(i, 1, n)
{
if(i > k)
{
s.erase(s.find(2 * p[i - k - 1]));
}
int x = 2 * p[i] - all;
auto it = s.lower_bound(x);
if(it != s.begin()) it--;
if(it != s.begin()) it--;
if(it != s.begin()) it--;
int cnt = 0;
while(cnt <= 6 && it != s.end())
{
int val = *it;
int y = all + val - 2 * p[i];
// cout << val / 2 << ' ' << p[i] << '\n';
// cout << y << '\n';
y = abs(y);
int big = (n + y) / 2, small = n - big;
maxz(ans, small);
cnt++;
it++;
}
s.insert(2 * p[i]);
}
cout << ans << '\n';
}
int32_t main()
{
#define task "cpp"
if (fopen(task".inp", "r"))
{
freopen(task".inp", "r", stdin);
freopen(task".out", "w", stdout);
}
cin.tie(0)->sync_with_stdio(0);
int t;
cin >> t;
while(t--)
{
solve();
}
//printclock;
return 0;
}