Binary String Minimizing CodeForces - 1256D(贪心)

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.
思路:思路挺好想的一道题,但是一不留心就出错。。
在规定的移动次数内,我们先在前面找出一个1,然后再其后面找出一个0.然后(尽可能的)交换位置。具体看代码
代码如下:

#include<bits/stdc++.h>
#define ll long long
using namespace std;

string s;
int n;
ll k;

int main()
{
	int t;
	scanf("%d",&t);
	while(t--)
	{
		scanf("%d%lld",&n,&k);
		cin>>s;
		int l=0,r;
		while(l<n&&s[l]=='0') l++;
		r=l+1;
		while(r<n&&s[r]=='1') r++;//起始位置一定要提前找出来,否则会出错或者超时。
		while(k)
		{
			while(l<n&&s[l]=='0') l++;
			while(r<n&&s[r]=='1') r++;
			if(l>=n||r>=n) break;
			if(k>=(r-l))
			{
				swap(s[l],s[r]);
				k-=(ll)(r-l);
				l++,r++;
			}
			else
			{
				swap(s[r-k],s[r]);//这就是尽可能的交换。
				k=0;
			}
		}
		cout<<s<<endl;
	}
	return 0;
}

努力加油a啊,(o)/~

发布了596 篇原创文章 · 获赞 47 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/starlet_kiss/article/details/105030326
今日推荐