http://oj.acm.zstu.edu.cn/JudgeOnline/problem.php?id=4437

题解:

首先map映射

然后从右往左依次走

其实题目很多都是废话,只要当前位数的权值比右边都大或者等于就是加,否则就是减。

/*
*@Author:   STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG

using namespace std;
typedef long long ll;
const int N=10000;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m;
char a[20];
int main()
{
#ifdef DEBUG
	freopen("input.in", "r", stdin);
	//freopen("output.out", "w", stdout);
#endif
    while(~scanf("%s",a)){
        int len=strlen(a);
        map<char,int>f;
        f['I']=1;
        f['V']=5;
        f['X']=10;
        f['L']=50;
        f['C']=100;
        f['D']=500;
        f['M']=1000;
        int maxl=f[a[len-1]];
        int ans=0;
        for(int i=len-1;i>=0;i--){
            if(maxl<=f[a[i]]){
                ans+=f[a[i]];
                maxl=max(maxl,f[a[i]]);
            }else{
                ans-=f[a[i]];
            }
        }
        cout << ans << endl;
    }

    //cout << "Hello world!" << endl;
    return 0;
}

C++版本二

#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;

int main()
{
    freopen("data2.in", "r", stdin);
    freopen("data2.out", "w", stdout);
	int v[500];
	v['I'] = 1;
	v['V'] = 5;
	v['X'] = 10;
	v['L'] = 50;
	v['C'] = 100;
	v['D'] = 500;
	v['M'] = 1000;
	char s[100];
	bool flag = true;
	int tmp = 0;
	while(scanf("%s", s) == 1)
	{
	    tmp++;
		int len = strlen(s);
		int ans = v[s[len-1]];
		for(int i=len-2; i>=0; --i)
		{
			if(v[s[i]] >= v[s[i+1]]) ans += v[s[i]];
			else ans -= v[s[i]];
		}
		printf("%d\n", ans);
	}

	return 0;
}