Codeforces Round #598 (Div. 3) D. Binary String Minimizing

You are given a binary string of length nn (i. e. a string consisting of nn 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 kk 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 ii and i+1i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.

You have to answer qq independent test cases.

Input

The first line of the input contains one integer qq (1q1041≤q≤104) — the number of test cases.

The first line of the test case contains two integers nn and kk (1n106,1kn21≤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 nn characters '0' and '1'.

It is guaranteed that the sum of nn over all test cases does not exceed 106106 (n106∑n≤106).

Output

For each test case, print the answer on it: the lexicographically minimum possible string of length nn you can obtain from the given one if you can perform no more than kk moves.

Example
input
Copy
3
8 5
11011010
7 9
1111100
7 11
1111100
output
Copy
01011110
0101111
0011111
Note

In the first example, you can change the string as follows: 110–––1101010–––111010011110–––1001110–––1100110–––111001011110110_11010→10_111010→011110_10→01110_110→0110_1110→01011110.

In the third example, there are enough operations to make the string sorted.

尽量把0往前移动

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    ios::sync_with_stdio(false);
    int q;
    cin >> q;
    while (q--) {
        int n;
        long long k;
        cin >> n >> k;
        string s;
        cin >> s;
        int j = 0;
        for (int i = 0; i < n; i++) {
            if (j < i) j = i;
            while (j < n && s[j] != '0') j++;  //判断前面某个0前面有几个1
            if (j < n && j - i <= k) {//判断能否直接换过去
                swap(s[i], s[j]);
                k -= j - i;
            }
        }
        cout << s << endl;
    }
    return 0;
}
原文地址:https://www.cnblogs.com/QingyuYYYYY/p/11802885.html