You are given two non-empty strings S and T of equal lengths. S contains the characters ‘0’, ‘1’and ‘?’, whereas T contains ‘0’ and ‘1’ only. Your task is to convert S into T in minimum number ofmoves. In each move, you can
1. change a ‘0’ in S to ‘1’
2. change a ‘?’ in S to ‘0’ or ‘1’
3. swap any two characters in S
As an example, suppose S = ”01??00” and T = ”001010”. We can transform S into T in 3 moves:
• Initially S = ”01??00”
• – Move 1: change S[2] to ‘1’. S becomes ”011?00”
• – Move 2: change S[3] to ‘0’. S becomes ”011000”
• – Move 3: swap S[1] with S[4]. S becomes ”001010”
• S is now equal to T
Input
The first line of input is an integer C (C ≤ 200) that indicates the number of test cases. Each caseconsists of two lines. The first line is the string S consisting of ‘0’, ‘1’ and ‘?’. The second line is thestring T consisting of ‘0’ and ‘1’. The lengths of the strings won’t be larger than 100.
Output
For each case, output the case number first followed by the minimum number of moves required toconvert S into T. If the transition is impossible,output ‘-1’ instead.
Sample Input
3
01??00
001010
01
10
110001
000000
Sample Output
Case 1: 3
Case 2: 1
Case 3: -1
这道题目虽然看起来好像是很难,可是仔细分析就那么几种情况,统计一下0和1还有?的数量还是很好分类讨论的,最后的换位置的环节,由于在我们前面两步的处理后两个字符串只剩下了0和1,这个时候差不多都是两个互换的情况,也就是解=不对的位置/2;
#include <iostream>
#include <cstring>
using namespace std;
char a[110],b[110];
int main()
{
int t,Case=1;
cin>>t;
while(t--)
{
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
cin>>a>>b;
int z1=0,z2=0,o1=0,o2=0,w=0,step=0;
for(int i=0;i<strlen(a);i++)
{
if(b[i]=='0')z2++;
else o2++;
if(a[i]=='?')w++;
else if(a[i]=='1')o1++;
else z1++;
}
if(z1+w<z2){cout<<"Case "<<Case++<<": "<<-1<<endl;continue;}
int i=0,bt=0;
while(w!=0)
{
if(a[i]=='?')
{
if(b[i]=='1'&&o1<o2){a[i]='1';o1++;w--;step++;}
else {a[i]='0';z1++;w--;step++;}
}
i++;
}
//cout<<z1<<" "<<z2<<endl;
if(z1!=z2)
{
int k=o2-o1,r=0;
for(int i=0;i<strlen(a);i++)
{
if(r==k)break;
if(a[i]!=b[i]&&a[i]=='0')
{
r++;
a[i]='1';
}
}
step+=r;
}
for(int i=0;i<strlen(a);i++)
{
if(a[i]!=b[i])bt++;
}
step=step+bt/2;
cout<<"Case "<<Case++<<": "<<step<<endl;
}
return 0;
}