You are given a binary string of length 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 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 and i+1 arbitrary (possibly, zero) number of times. Each such swap is considered a separate move.
You have to answer q independent test cases.
Input
The first line of the input contains one integer q (1≤q≤104) — the number of test cases.
The first line of the test case contains two integers n and 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 characters ‘0’ and ‘1’.
It is guaranteed that the sum of n over all test cases does not exceed 106 (∑n≤106).
Output
For each test case, print the answer on it: the lexicographically minimum possible string of length n you can obtain from the given one if you can perform no more than 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: 110−−11010→10−−111010→011110−−10→01110−−110→0110−−1110→01011110.
In the third example, there are enough operations to make the string sorted.
题意:
给出一个字符串,最多可以移动K次,每次可以交换i,i+1的位置的数,这个串只有0和1组成。问在k次移动次数范围内,尽可能使得结果字典序最小。
分析:
要字典序最小,既然题目给出0,1串,那么0必定要往前面放置,才会是整体字典序最小。一位大佬给我提供一种很好的方法,我讲解下。
大体思想就是:把0往前放,直到k次用完结束,或者字符串已经跑完了。整体复杂度O(n)。
首先我们找到第一个1的位置,用num来记录,for循环去遍历,当遍历到0的时候,说明要移动了,那么要移动到哪呢,因为刚刚记录了第一个1的位置,i-num就是当前0和最前面的1的距离,这个距离呢就是要移动的个数,i-num<k 时,交换swap(s[i],s[num]); 并且把k减掉用去的,num++,移动到下一个1的位置。
下面的图方便理解:
AC代码: (注意k的大小)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
int const N=1e6+100;
ll t,n,k;
char s[N];
int main()
{
scanf("%lld",&t);
while(t--)
{
scanf("%lld%lld",&n,&k);
scanf("%s",s+1);
ll i=0;
ll num=0;
while(s[num]!='1')num++,i++;
for(;i<=n;i++)
{
if(s[i]=='0')
{
if(i-num<k)
{
swap(s[i],s[num]);
k-=(i-num);
num++;
}
else if(i-num>=k)
{
swap(s[i],s[i-k]);
k=0;
break;
}
}
}
// for(int i=1;i<=n;i++)
// {
// cout<<s[i];
// }
// cout<<endl;
cout<<s+1<<endl;
}
return 0;
}