D. Binary String Minimizing(Codeforces Round #598 (Div. 3))(模拟)
time limit per test:1 second
memory limit per test:256 megabytes
input:standard input
output:standard output
Description
You are given a binary string of length
n
n
n (i. e. a string consisting of n characters '0'
and '1'
).
In one move you can swap two adjacent characters of the string. What is the lexicographically minimum possible string you can obtain from the given one if you can perform no more than k k k moves? It is possible that you do not perform any moves at all.
Note that you can swap the same pair of adjacent characters with indices i i i and i + 1 i+1 i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q q q independent test cases.
Input
The first line of the input contains one integer q ( 1 ≤ q ≤ 1 0 4 ) q (1≤q≤10^4) q(1≤q≤104) — the number of test cases.
The first line of the test case contains two integers n n n and k ( 1 ≤ n ≤ 1 0 6 , 1 ≤ k ≤ n 2 ) k (1≤n≤10^6,1≤k≤n^2) k(1≤n≤106,1≤k≤n2) — the length of the string and the number of moves you can perform.
The second line of the test case contains one string consisting of
n
n
n characters '0'
and '1'
.
It is guaranteed that the sum of n n n over all test cases does not exceed 1 0 6 ( ∑ n ≤ 1 0 6 ) 10^6 (∑n≤10^6) 106(∑n≤106).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n n n you can obtain from the given one if you can perform no more than k k k moves.
Example
input
3
8 5
11011010
7 9
1111100
7 11
1111100
output
01011110
0101111
0011111
Note
In the first example, you can change the string as follows: 11011010 → 10111010 → 01111010 → 01110110 → 01101110 → 01011110 11011010→10111010→01111010→01110110→01101110→01011110 11011010→10111010→01111010→01110110→01101110→01011110.
In the third example, there are enough operations to make the string sorted.
题解
保存所有0的位置,然后依次贪心地把0往前移动即可
代码
#include <iostream>
#include <algorithm>
#include <vector>
#define maxn 1000005
#define _for(i, a) for(LL i = 0; i < (a); i++)
using namespace std;
typedef long long LL;
char a[maxn];
vector<LL> c;
LL n, k;
void init() {
c.clear();
}
void sol() {
for (LL i = 0; a[i]; i++) {
if (a[i] == '0') c.push_back(i);
}
LL t = 0, pos = 0;
while (t < c.size() && k > 0 && pos < n) {
while (a[pos] == '0') pos++;
if (c[t] < pos) {
t++;
continue;
}
LL tem = min(c[t] - pos, k);
swap(a[c[t]], a[c[t] - tem]);
k -= tem;
pos++;
t++;
}
cout << a << "\n";
}
int main() {
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
//freopen("in.txt", "r", stdin);
LL T;
cin >> T;
_for(q, T) {
init();
cin >> n >> k;
cin >> a;
sol();
}
return 0;
}
/*
in:
2
5 3
00011
10 5
1010101010
ans:
00011
0010111010
*/