【codechef】Devu and binary String(字符串不超过连续k个相同,最少改几个,分类)


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
*/ 


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值