题解:P17953 [NCPC 2023] Converting Romans
shuimendawang · · 题解
题意
输入
| 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;
}
:::