#46358: 速解


ericycl1118@gmail.com (那一天的憂鬱 憂鬱起來)

學校 : 高雄市立高雄高級中學
編號 : 175154
來源 : [61.227.60.175]
最後登入時間 :
2025-06-23 06:08:20

步驟1 將輸入轉成數字,方便計算與判斷 (技巧:倒序遍歷)
步驟2 將計算結果轉成羅馬數字 (技巧:貪心演算法)
 
#include <bits/stdc++.h>
using namespace std;
int r2i(string s){
    unordered_map<char, int> roman = {
        {'I',1},{'V',5},{'X',10},{'L',50},
        {'C',100},{'D',500},{'M',1000}
    }; 
    int result=0, prev_value=0;
    for(int i = s.size()-1; i>=0; i--) { // 從右到左遍歷
        int current_value = roman[s[i]];
        if(current_value < prev_value) {
            result -= current_value; // 減法
        } else {
            result += current_value; // 加法
        }
        prev_value = current_value; // 更新前一個值
    }
    return result;
}
string i2r(int i){
    int values[] = {1000,900,500,400,100,90,50,40,10,9,5,4,1};
    string symbols[] = {"M","CM","D","CD","C","XC","L","XL","X","IX","V","IV","I"};
    string result = "";
    for(int j = 0; j < 13; j++) { // 由大到小遍歷
        while(i >= values[j]) {
            result += symbols[j];
            i -= values[j];
        }
    }
    return result;
}
int main() {
    //ios::sync_with_stdio(false);
    //cin.tie(0);
    string a,b;
    int ans;
    while(cin>>a>>b){
        if(a=="#") break;
        ans=abs(r2i(a)-r2i(b));
        cout << (ans ? i2r(ans) : "ZERO") << endl;
    }
    return 0;
}