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)/~

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

starlet_kiss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值