sgu546 Ternary Password

题目链接:http://acm.sgu.ru/problem.php?contest=0&problem=546

这题还好,1Y,考虑情况周全,就没问题了,还好提交之前把想到的情况都测试了一遍..

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <cstring>
 5 #include <algorithm>
 6 char s[202];
 7 int n, a, b, a0[202], b0[202];
 8 int main(void) {
 9     //freopen("in.txt", "r", stdin);
10     while (~scanf("%d%d%d%s", &n, &a, &b, s)) {
11         int a1 = 0, b1 = 0;
12         for (int i = 0;i < n; ++i) {
13             if (s[i] == '0') a0[a1] = i, a1++; else if (s[i] == '1') b0[b1] = i, b1++;
14         }
15         if (a1 == a && b1 == b) printf("0
%s
", s);
16         else if (a+b>n) printf("-1
");
17         else {
18             int cnt = 0, a2 = 0, b2 = 0;
19             a2 = a1-a, b2 = b1-b;
20             if (a1 < a) {
21                 for (int f = 0; f < b2 && a1 < a; ++f) s[b0[f]] = '0', cnt++, a1++, b1--;
22                 if (a1 < a) {
23                     for (int e = 0; e < n && a1 < a; ++e) if (s[e] == '2') s[e] = '0', cnt++, a1++;
24                 }
25             }
26             if (b1 < b) {
27                 for (int f = 0; f < a2 && b1 < b; ++f) s[a0[f]] = '1', cnt++, b1++, a1--;
28                 if (b1 < b) {
29                     for (int e = 0; e < n && b1<b; ++e) if (s[e] == '2') s[e] = '1', cnt++, b1++;
30                 }
31             }
32             if (a1 > a) {
33                 for (int f = 0; f < n && a1 > a; ++f) if (s[f] == '0') a1--, s[f] = '2', cnt++;
34             }
35             if (b1 > b) {
36                 for (int f = 0; f < n && b1 > b; ++f) if (s[f] == '1') b1--, s[f] = '2', cnt++;
37             }
38             printf("%d
%s
", cnt, s);
39         }
40     }
41 
42     return 0;
43 }

只是我的方法貌似比较笨==

原文地址:https://www.cnblogs.com/liuxueyang/p/3198675.html