Binary String Minimizing
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.
比较思维的题目,细节真的多,k要为longlong型,每次记录0前面有多少个1,判断k是否满足0前进所需的1步数就行;
#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define lson k<<1
#define rson k<<1|1
//ios::sync_with_stdio(false);
using namespace std;
const int N=100010;
const int M=200100;
const LL mod=1e9+7;
int v1[1000100];
int a[1000100];
int main(){
ios::sync_with_stdio(false);
int t;
cin>>t;
while(t--){
int n;
LL k;
cin>>n;
cin>>k;
string s;
cin>>s;
int ans1=0;
for(int i=0;i<s.length();i++){
if(s[i]=='0'){
v1[i+1]=ans1;
a[i+1]=0;
}
else{
ans1++;
a[i+1]=1;
}
}
for(int i=1;i<=n;i++){
if(v1[i]){
if(k>=(LL)v1[i]){
a[i-v1[i]]=0;
a[i]=1;
k=k-(LL)v1[i];
}
else if(k!=0){
int b=(int)k;
a[i-b]=0;
a[i]=1;
break;
}
}
}
for(int i=1;i<=n;i++){
if(a[i]) cout<<1;
else cout<<0;
a[i]=0;
v1[i]=0;
}
cout<<endl;
}
return 0;
}

这是一道关于二进制字符串操作的问题。给定一个长度为n的二进制字符串,通过不超过k次交换相邻字符的操作,求能得到的字典序最小的字符串。注意,相同的字符对可以被交换任意多次,每交换一次计为一次操作。对于q个独立的测试用例,需要求解满足条件的最小字符串。输入包含字符串长度n、允许的操作次数k以及原始字符串,需要确保总长度不超过10^6。解答时需关注细节,如k应为longlong类型,并计算0前进所需的1的步数来判断操作可行性。
1327

被折叠的 条评论
为什么被折叠?



