// 演算法 / Algorithm:
//   與 C 版相同 — 線性掃描,若當前符號小於右鄰則減,否則加。
//   差別:用 unordered_map<char,int> 當查找表,寫法更貼近現代 C++。
//   Same algorithm as the C version — linear scan, subtract when current
//   symbol is smaller than its right neighbor, otherwise add.
//   Implementation uses unordered_map<char,int> for an idiomatic C++ lookup.

#include <string>
#include <unordered_map>

class Solution {
public:
    int romanToInt(std::string s) {
        // unordered_map 是 STL 雜湊表,鍵→值平均 O(1) 查找
        // unordered_map is the STL hash map — average O(1) lookup by key.
        // 用 static const 避免每次呼叫都重建這張表 / static const avoids rebuilding the table per call.
        static const std::unordered_map<char, int> value = {
            {'I', 1},    {'V', 5},    {'X', 10},   {'L', 50},
            {'C', 100},  {'D', 500},  {'M', 1000},
        };

        int total = 0;                       // 累積答案 / running total
        int n = static_cast<int>(s.size());  // 字串長度 / string length

        // 從左到右逐字元處理 / process each character left to right.
        for (int i = 0; i < n; i++) {
            // .at(key) 回傳對應的值;若鍵不存在會丟例外 (本題保證合法,不會發生)
            // .at(key) returns the mapped value; throws if missing (guaranteed not to happen here).
            int cur = value.at(s[i]);

            // 判斷是否為「減法配對」的左半部:有右鄰且比右鄰小
            // Check the subtractive-pair rule: a right neighbor exists and current < neighbor.
            if (i + 1 < n && cur < value.at(s[i + 1])) {
                total -= cur;                // 減 / subtract
            } else {
                total += cur;                // 加 (包含最後一個字元) / add (also handles last char)
            }
        }

        return total;                        // 結果 / answer
    }
};
