SGU546
题意:给出一个只可能包含0,1,2的字符串,给定需要的0的个数a和需要的1的个数b,使用最少的替换次数得到目标串,输出交换次数。做法:简单模拟即可代码:
#include <algorithm> #include <iostream> #include <stdio.h> #include <string> using namespace std; int main() { int n,a,b; string s; while(cin>>n>>a>>b>>s) { if(a+b>n) {puts("-1");continue;} int c = n-a-b, i; int x=count(s.begin(),s.end(),'0'); int y=count(s.begin(),s.end(),'1'); int z=count(s.begin(),s.end(),'2'); int ans=0; for(i=0; i<n; i++){ if(s[i]=='0' && x>a || s[i]=='1'&&y>b || s[i]=='2'&&z>c){ ans++; if(s[i]=='0') x--; if(s[i]=='1') y--; if(s[i]=='2') z--; if(x<a){x++,s[i]='0';} else { if(y<b){y++,s[i]='1';} else if(z<c){z++,s[i]='2';} } } } cout<<ans<<endl; cout<<s<<endl; } return 0; }
Greatness is never a given, it must be earned.