定义:one zero表示原串的0和1的个数 one1和zero1表示目的串的0和1的个数
分三种情况:
1、原串的0的个数和?个数和小于目的串0个数,一定输出-1
2、原串0多于目的串,那么先用?变换成1,选取对应目的串也是1的位置先变,如果不够再将其他?变成1,如果还不够找目的串相对位置为1的0变成1.......
3、原串1个数少于目的串,那么说明原串0,多了,先把1补全,然后其他的?换成0,用的也是贪心的思路,和上面情况2类似
总之能用?的要用?
#include <iostream>
#include <string.h>
#include <algorithm>
#include <stdio.h>
using namespace std;
#define maxn 500
char begin[maxn],end[maxn];
int zero,one,zero1,one1;
int main(){
int i,j,k,t,len,ans,now,cas=0;
scanf("%d",&t);
while(t--){
scanf("%s%s",begin,end);
printf("Case %d: ",++cas);
zero=one=zero1=one1=0;
ans=0;
len=strlen(begin);
for(i=0;i<len;i++){
if(begin[i]=='0')zero++;
else if(begin[i]=='1')one++;
if(end[i]=='0')zero1++;
else if(end[i]=='1')one1++;
}
if(len-one<zero1){//case 1
printf("-1\n");
continue;
}
if(zero<=zero1){//case 2 zero can only change by '?'
k=zero1-zero;
for(i=0;i<len&&k>0;i++){
if(begin[i]=='?'&&end[i]=='0')
begin[i]='0',ans++,k--;
}
for(i=0;i<len && k>0;i++)
if(begin[i]=='?')begin[i]='0',ans++,k--;
for(i;i<len;i++)if(begin[i]=='?') begin[i]='1',ans++;
now=0;
for(i=0;i<len;i++)
if(begin[i]!=end[i])now++;
ans+=now/2;
printf("%d\n",ans);
continue;
}
if(one<=one1){
k=one1-one;
for(i=0;i<len&&k>0;i++)if(begin[i]=='?'&&end[i]=='1')begin[i]='1',ans++,k--;
if(k>0){
for(i=0;i<len&&k>0;i++)if(begin[i]=='?')begin[i]='1',ans++,k--;
if(k>0){
for(i=0;i<len&&k>0;i++)if(begin[i]=='0'&&end[i]=='1')begin[i]='1',ans++,k--;
for(i=0;i<len&&k>0;i++)if(begin[i]=='0'&&end[i]!='0')begin[i]='1',ans++,k--;
for(i=0;i<len&&k>0;i++)if(begin[i]=='0')begin[i]='1',ans++,k--;
}
}
for(i=0;i<len;i++)if(begin[i]=='?') begin[i]='0';
now=0;
for(i=0;i<len;i++)if(begin[i]!=end[i])now++;
ans+=now/2;
printf("%d\n",ans);
}
}
return 0;
}