题解:P17953 [NCPC 2023] Converting Romans

· · 题解

题意

输入 n 个罗马数字,把这些罗马数字转化为阿拉伯数字。

I V X L C D M
1 5 10 50 100 500 1000

分析

写一个函数判断当前位的值,从右往左遍历罗马数字,维护最大值 mx。

:::success[代码]

#include<bits/stdc++.h>
using namespace std;
int n;
string st;
int check(char s){
    switch(s){
        case 'I':return 1;
        case 'V':return 5;
        case 'X':return 10;
        case 'L':return 50;
        case 'C':return 100;
        case 'D':return 500;
        case 'M':return 1000;
    }
}
int main(){
    cin.tie(nullptr)->sync_with_stdio(false);
    cin>>n;
    while(n--){
        int mx=0,ans=0;
        cin>>st;
        for(int i=st.size()-1;i>=0;i--){
            int t=check(st[i]);
            if(t>=mx)ans+=t,mx=t;
            else ans-=t;
        }
        cout<<ans<<'\n';
    }

    return 0;
}

:::