1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| unordered_map<string, int> numMap{ { "I", 1 }, { "II", 2 }, { "III", 3 }, { "IV", 4 }, { "V", 5 }, { "VI", 6 }, { "VII", 7 }, { "VIII", 8 }, { "IX", 9 }, { "X", 10 }, { "XX", 20 },{ "XXX", 30 },{ "XL", 40 },{ "L", 50 }, { "LX", 60 },{ "LXX", 70 },{ "LXXX", 80 },{ "XC", 90 } };
int getNum(const string& num) { string digit = ""; int curNum = 100; int i = 0; for (; i < num.size(); ++i) { if (num[i] != 'I' && num[i] != 'V') digit += num[i]; else break; } if (i == 0) { if (numMap.find(num) != numMap.end()) curNum = numMap[num]; } else { string unit = num.substr(i, num.size()); if (numMap.find(digit) != numMap.end() && numMap.find(unit) != numMap.end()) curNum = numMap[unit] + numMap[digit]; } return curNum; }
void swap(string& s, int i, int j) { char c = s[i]; s[i] = s[j]; s[j] = c; }
void fullArray(string& num, int idx, string& minStr, int& minNum) { if (idx >= num.size()) { int tmp = getNum(num); if (tmp < minNum) { minNum = tmp; minStr = num; } return; }
for (int i = idx; i < num.size(); ++i) { swap(num, i, idx); fullArray(num, idx + 1, minStr, minNum); swap(num, i, idx); } }
int main() { string num; while (cin >> num) { int cur = getNum(num); int minNum = cur; string minStr = num;
fullArray(num, 0, minStr, minNum); cout << minStr << endl; } return 0; }
|