Input: 3 2 1 11 2 2 11 4 1 1001 Output: 1 10 0 11 2 1010
http://www.codechef.com/MAY15/problems/DEVSTR
我的思路:一开始的想法是直接暴力枚举1-n位二进制的所有数,不过超时了(20分)
后来的想法是贪心。它的意思是尽量少改几个数,而需要改的地方只有在0或1超过k个的时候,那么在每一段连续的0或1里,我们可以每隔k位设置成相反的数字。当然这里要注意比如1100011这种情况,如果按上面改的话会变成1100111,这个时候就应该把在这一段连续数末尾要改的数提前一位(肯定符合,因为这是以k>=2来考虑的)。k=1与k>1要分开来考虑。
#include<iostream>
#include<algorithm>
#include<string>
#include<map>
#include<vector>
#include<cmath>
#include<queue>
#include<string.h>
#include<stdlib.h>
#include<stdio.h>
#define ll long long
#define mod 1000000007
using namespace std;
string x;
int main(){
int t;
cin>>t;
while(t--){
int n,m;
cin>>n>>m;
cin>>x;
int s1=0,s2=0,s=0;
string x1,x2,x3;
if(m==1){
int s1=0;s2=0;
for(int i=0;i<n;++i){
if(i%2==0){
if(x[i]=='1')
s1++;
else
s2++;
}
else{
if(x[i]=='1')
s2++;
else
s1++;
}
}
if(s1<s2){
cout<<s1<<endl;
for(int i=0;i<n;++i){
if(i%2==0)
cout<<0;
else
cout<<1;
}
}
else{
cout<<s2<<endl;
for(int i=0;i<n;++i){
if(i%2==0)
cout<<1;
else
cout<<0;
}
}
cout<<endl;
}
else{
x1=x;x2=x;
int i,a=0,b=0;
for(i=0;i<n;++i){
if(x[i]=='1'){
a++;
b=0;
}
else{
b++;
a=0;
}
if(a>m){
int p=i;
if(i<n-1&&x[i+1]=='0'){
p--;
b=0;
a=1;
}
else{
b=1;
a=0;
}
x1[p]=(x[p]=='1'?'0':'1');
s++;
}
else if(b>m){
int p=i;
if(i<n-1&&x[i+1]=='1'){
p--;
b=1;
a=0;
}
else{
b=0;
a=1;
}
x1[p]=(x[p]=='1'?'0':'1');
s++;
}
}
cout<<s<<endl<<x1<<endl;
}
}
return 0;
}
/*
4
7 2
1100011
12 2
111101000110
8 2
11111100
8 2
11111001
*/