Zoj problem set-3829 known notation (Greedy)
Question Link
question: Give You A suffix expression (only digits and symbols), but the space of this suffix expression is unfortunately lost, now I will give you a suffix expression like this, asking you at least how many operations are required to turn this expression into legal.
operation:
1. Insert'' or a number (one-digit) anywhere in the expression ).
2. Swap the characters at any two positions of the expression.
Solution:
At first, I thought it was complicated, and the result was still missing some kind of situation, so I couldn't go through it all the time; that is, when I got stuck with '', the numbers were not enough to be inserted or replaced.
In fact, just think like this: first, the number of numbers should at least be the number of symbols + 1. First, calculate the number of numbers and symbols. If a number is not enough to be inserted, it is better to replace it. If a number is inserted at the beginning, the better it is. If a number is inserted at the beginning, the better it is, the better it is.
Note: all are numbers.
Code:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;const int maxn = 1005;char str[maxn];int main () { int T; scanf ("%d", &T); while (T--) { scanf ("%s", str); int num, op, ans; int len = strlen (str); ans = num = op = 0; for (int i = 0; i < len; i++) if (str[i] == ‘*‘) op++; num = len - op; if (!op) { printf ("0\n"); continue; } if (str[len - 1] != ‘*‘) { ans++; for (int i = 0; i < len; i++) if (str[i] == ‘*‘) { swap(str[i], str[len - 1]); break; } } int cnt = 0; for (int i = 0; i < len; i++) { if (str[i] == ‘*‘) { if (cnt > 1) cnt--; else { if (num >= op + 1) { for (int j = len - 1; j >= 0; j--) if (str[j] != ‘*‘) { swap(str[j], str[i]); cnt++; ans++; break; } } else { ans++; num++; if (!cnt) { i--; cnt = 1; } } } } else cnt++; } printf ("%d\n", ans); } return 0;}
Zoj problem set-3829 known notation (Greedy)