uva12545 Bits Equalizer
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 of moves. In each move, you can
- change a `0' in S to `1'
- change a `?' in S to `0' or `1'
- 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 (C200) that indicates the number of test cases. Each case consists of two lines. The first line is the string S consisting of `0', `1' and `?'. The second line is the string 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 to convert 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
这个题目用到的是统计的思想,不用真正的去变字符串里字符的位置,只需要统计哪几个要变动就OK。
#include <algorithm> #include <iostream> #include <cstdio> #include <cstring> using namespace std; const int MAXN = 255; int num[4]; char S[MAXN], T[MAXN]; int solve(int len) { memset(num, 0, sizeof(num)); for(int i = 0; i < len; ++i) { if(S[i] == '0' && T[i] == '1' ) num[0]++; else if(S[i] == '1' && T[i] == '0') num[1]++; else if(S[i] == '?' && T[i] == '1') num[2]++; else if(S[i] == '?' && T[i] == '0') num[3]++; } int ans = min(num[0], num[1]); if(num[0] >= num[1]) { num[0] -= ans; if(num[3] - num[0] >= 0) { ans += 2*num[0]; ans += num[2] + num[3] - num[0]; } else { ans += 2*num[3]; ans += num[2] + num[0] - num[3]; } } else if(num[0] < num[1]) { num[1] -= ans; if(num[2] - num[1] >= 0) { ans += 2*num[1]; ans += num[3] + num[2] - num[1]; } } return ans; } int main() { int Tcase, ans; int tag1, tag2; scanf("%d%*c", &Tcase); for(int t = 1; t <= Tcase; ++t) { tag1 = 0, tag2 = 0; ans = 0; gets(S); gets(T); int len = strlen(S); for(int i = 0; i < len; ++i) { if(S[i] == '1') tag1++; if(T[i] == '1') tag2++; } if(tag1 > tag2 ) printf("Case %d: %d ", t, -1); else { printf("Case %d: %d ", t, solve(len)); } } return 0; }