跳到正文

题解

题解:P17953 [NCPC 2023] Converting Romans

shuimendawang约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年11月23日
收录
2026年11月28日
更新
2026年11月28日
篇幅
约 2 分钟
题目
P17953

版本

  1. v1当前

题意

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

IVXLCDM
1510501005001000

分析

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

  • 若当前位的数大于 mxmx,就将结果加上当前位,并更新最大值。
  • 否则减去当前位,因为小的在大的前面就是减法计数。
代码
C++
#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;
}
原文