Codeforces Gym 100203E E - bits-Equalizer 贪心
E - bits-Equalizer
Time Limit: 20 Sec
Memory Limit: 256 MB
题目连接
http://acm.hust.edu.cn/vjudge/contest/view.action?cid=87794#problem/K
Description
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:
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 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
HINT
题意
给你一个s1和s2,你每次有三种操作,第一种是将0变成1,第二种是把问号变成1或者0,第三种是交换任意两个字符的位置
题解:
贪心,首先处理问号,然后再处理0变成1的问题,最后处理交换位置的问题
每次处理都直接扫一遍就好了
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <algorithm> using namespace std; string s1,s2; int num1x,num1y,num2x,num2y; int main() { int t; scanf("%d",&t); for(int cas=1;cas<=t;cas++) { num1x=num1y=num2x=num2y=0; cin>>s2>>s1; int len=s1.size(); for(int i=0;i<len;i++) { if(s1[i]=='1') num1x++; if(s1[i]=='0') num1y++; if(s2[i]=='1') num2x++; if(s2[i]=='0') num2y++; } int flag=0; int ans=0; for(int i=0;i<len;i++) { if(num2x>num1x) { flag=1; break; } if(s2[i]=='?') { if(s1[i]=='1') { if(num2x<num1x) { s2[i]='1'; num2x++; ans++; } else { s2[i]='0'; num2y++; ans++; } } else { if(num2y<num1y) { s2[i]='0'; num2y++; ans++; } else { s2[i]='1'; num2x++; ans++; } } } } if(flag==1) { printf("Case %d: -1\n",cas); continue; } for(int i=0;i<len;i++) { if(num1x==num2x&&num2x==num2y) break; if(s2[i]=='0'&&s1[i]=='1') { if(num1x>num2x) { num2y--; num2x++; s2[i]='1'; ans++; } } } int tmp=0; for(int i=0;i<len;i++) { if(s1[i]!=s2[i]) { tmp++; } } printf("Case %d: %d\n",cas,ans+tmp/2); } }