题解:P17953 [NCPC 2023] Converting Romans
Zhiyuan2012 · · 题解
P17953
::::info[思路]
首先题目中说,如果较小的数码出现在较大的数码之前,就从较大的数码中减去较小的数码。
所以我们可以考虑倒序遍历字符串
令
设遍历的下标为
遍历
- 如果
\text{maxs}<s_i ,则s_i 对\text{ans} 的贡献为\text{roman}(m) 。 - 否则
s_i 对\text{ans} 的贡献为-\text{roman}(m) ,并且更新\text{maxs} 为\text{roman}(m) 。
| 最后输出 |
|---|
| ::::success[部分代码] |
| ```cpp |
| while(n--) |
| { |
| int ans=0,maxs=0;//每次都要清零 |
| cin>>s; |
| for(int i=s.length()-1;i>=0;i--) |
| { |
| int ss=roman(s[i]);//转为阿拉伯数字 |
| if(maxs<=ss) |
| { |
| maxs=ss;//记录最大的数 |
| ans+=ss; |
| } |
| else |
| { |
| ans-=ss; |
| } |
| } |
| cout<<ans<<"\n"; |
| } |
| ``` |
| :::: |