Problem:


ローマ数字

古代ローマでは数を数えることは難しい仕事でした。アラビア数字の 0,1,2,3,…, 9 はまだ流布していませんでした。その代わり次のような記号が使われていました。

アラビア数字ローマ数字アラビア数字ローマ数字アラビア数字ローマ数字

1I11XI30XXX

2II12XII40XL

3III13XIII50L

4IV14XIV60LX

5V15XV70LXX

6VI16XVI80LXXX

7VII17XVII90XC

8VIII18XVIII100C

9IX19XIX500D

10X20XX1000M

I は 1、 V は 5、 X は 10、 L は 50、 C は 100、 D は 500、 M は 1000、 他の例は上の表を見てください。小さい数が大きい数に続いている、つまり右側にあるときは足し算をします。小さい数が大きい数の前に、つまり左にあるときは、大きい数から小さい数を引きます。大きい数字の前にあって引き算を表す小さな数字は一回の引き算あたりひとつしかありません。

ローマ数字をアラビア数字（通常の数字）の表記（10 進表示）に変換して出力するプログラムを作成してください。ただし、与えられるローマ数字は上記のルールにのみ従っています(実際のローマ数字の表記にはもっと細かいルールがありますが、ここでは考慮する必要はありません。たとえば、実際のローマ数字ではI はV かX から、X はL かC から、C はD かM からしか引き算しませんし、同じローマ数字は４つ以上（または５つ以上）足し並べることはありません。)

Input

複数のデータセットが与えられます。それぞれのデータセットにローマ数字（半角大文字のI, V, X, L, C, D ,M で表される連続した文字列）が１行に与えられます。与えられるローマ数字の文字列の長さはおのおの 100 以下です。

データセットの数は 50 を超えません。

Output

各データセットに対し、アラビア数字（整数）を１行に出力して下さい。

Sample Input

IV
CCCCLXXXXVIIII
CDXCIX

Output for the Sample Input

4
499
499



Sample input:
IV
CCCCLXXXXVIIII
CDXCIX


Sample output:
4
499
499

Submission status: Wrong Answer

Solution code:

def Roman_numerals(x):
	if x=='I':
		return 1
	elif x=='V':
		return 5
	elif x=='X':
		return 10
	elif x=='L':
		return 50
	elif x=='C':
		return 100
	elif x=='D':
		return 500
	elif x=='M':
		return 1000




while True:
	try:
		s=0
		string=input()
		for i in range(len(string)):
			tmp_now =Roman_numerals(string[i:i+1])
			tmp_next=Roman_numerals(string[i+1:i+2])
			if (tmp_now==1 and tmp_next==5):
				s+=-1
			elif (tmp_now==1 and tmp_next==10):
				s+=-1
			elif (tmp_now==10 and tmp_next==50):
				s+=-10
			elif (tmp_now==10 and tmp_next==100):
				s+=-10
			elif (tmp_now==100 and tmp_next==500):
				s+=-100
			else:
				s+=tmp_now
		print(s)

	except EOFError:
		break

Submission status: Wrong Answer

Solution code:
_input = input()

d = {
    'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000
}


def solve(roma):
    roma_nums = [d[c] for c in roma]
    _sum = 0
    for i, num in enumerate(roma_nums):
        if i == 0 or i == len(roma_nums) - 1:
            _sum += num
            continue
        else:
            try:
                next_num = roma_nums[i + 1]
            except IndexError:
                break

            if next_num <= num:
                _sum += num
            else:
                _sum -= num

    return _sum


if __name__ == '__main__':
    print(solve(_input))

Submission status: Wrong Answer

Solution code:
dict = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}

while True:
    try:
        roman = raw_input()
        sum = 0
        for i in range(len(roman)):
            print roman[i]
            sum += dict[roman[i]]
        sum -= 2*roman.count("IV")
        sum -= 2*roman.count("IX")
        sum -= 20*roman.count("XL")
        sum -= 20*roman.count("XC")
        sum -= 200*roman.count("CD")
        sum -= 200*roman.count("CM")
        print sum
    except:
        break

Submission status: Accepted

Solution code:
dic = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}

while(True):
    try:
        lis = list(input())
        ans = [dic[e] for e in lis]
        print(sum([-ans[i] if ans[i]<ans[i+1] else ans[i] for i in range(len(ans)-1)] + [ans[-1]]))
    except:
        break

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from sys import *

lis = {"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000,"\n":0}

for s in stdin:
  num = 0
  for i in xrange(len(s)-1):
    if lis[s[i]] < lis[s[i+1]]: num -= lis[s[i]];
    else: num += lis[s[i]]
  print num

Submission status: Accepted

Solution code:
import sys
for l in sys.stdin:
	s=0
	d=[[100,500,0,0,0,5,1,10,0,50,1000][(n-67)%14]for n in map(ord,l.strip())]
	for i,j in zip(d,d[1:]+[0]):s+=-i if i<j else i
	print s

Submission status: Accepted

Solution code:
import sys
for l in sys.stdin:
	s=0
	d=[[100,500,0,0,0,5,1,10,0,50,1000,0,0,0][(n-67)%14]for n in map(ord,l)]
	for i,j in zip(d,d[1:]+[0]):s+=-i if i<j else i
	print s

Submission status: Accepted

Solution code:
import sys
for l in sys.stdin:
	s=0
	d=[[0,0,5,1,10,0,50,1000,0,0,0,100,500,0][n%14]for n in map(ord,l)]
	for i,j in zip(d,d[1:]+[0]):s+=-i if i<j else i
	print s

Submission status: Accepted

Solution code:
def brain(l):
    c = l[1] - l[0]
    if 0 < c:
        result.append(c)
        del lis[0]
        del lis[0]
    else:
        lis.append(l[0])
        del lis[0]
        
def cisco(l):
    for i in range(len(l)):
        if l[i] == 'I':
            l[i] = 1
        elif l[i] == 'V':
            l[i] = 5
        elif l[i] == 'X':
            l[i] = 10
        elif l[i] == 'L':
            l[i] = 50
        elif l[i] == 'C':
            l[i] = 100
        elif l[i] == 'D':
            l[i] = 500
        elif l[i] == 'M':
            l[i] = 1000
    return l

while True:
    result = []
    try:
        lis = list(raw_input())+['*']
        while lis:
            if not (lis[0] == '*' or lis[1] == '*'):
                l = cisco([lis[0], lis[1]])
                brain(l)
            elif lis[0] == '*':
                del lis[0]
                break
            elif lis[1] == '*':
                l = cisco([lis[0]])
                lis.append(l[0])
                del lis[0]
                del lis[0]
                break
        result.append(sum(lis))
        print sum(result)
    except EOFError:
        break

Submission status: Accepted

Solution code:
import sys

def dec_num(x):
    for i in range(len(x)):
        if x[i] == 2:
            x[i] = 5
        elif x[i] == 3:
            x[i] = 10
        elif x[i] == 4:
            x[i] = 50
        elif x[i] == 5:
            x[i] = 100
        elif x[i] == 6:
            x[i] = 500
        elif x[i] == 7:
            x[i] = 1000

def to_index(x):
    if x == 1:
        return 1
    elif x == 5:
        return 2
    elif x == 10:
        return 3
    elif x == 50:
        return 4
    elif x == 100:
        return 5
    elif x == 500:
        return 6
    elif x == 1000:
        return 7


def toNum(x):
    result = 0
    tmp = x[0]
    for i in range(len(x)):
        if tmp < x[i]:
            result += x[i]-tmp
        elif i < len(x)-1 and x[i] < x[i+1]:
            result += 0
        else:
            result += x[i]
        tmp = x[i] 

    return result

for line in sys.stdin.readlines():
    line = line.translate(str.maketrans('IVXLCDM', '1234567'))
    num = list(map(int, (' '.join(line)).split()))
    dec_num(num)
    print(toNum(num))

Submission status: Accepted

Solution code:
#"memo roiti 875674"
d={"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}

while 1:
    try:
        n=raw_input()
        t=0
        value=1000
        for i in n:
            if value>=d[i]:
                value=d[i]
                t=t+value
            else:
                t=t-value*2
                value=d[i]
                t=t+value
        print t
    except:
        break

Submission status: Accepted

Solution code:
import sys
def todec(s):
    roman_dic = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    ret, prev = 0, 0
    for i in reversed(s):
        d = roman_dic[i]
        if d < prev:
            ret -= d
        else:
            ret += d
        prev = d
    return ret

A = sys.stdin.read().split()
for a in A:
    print(todec(a))

Submission status: Accepted

Solution code:

def Roman_numerals(x):
	if x=='I':
		return 1
	elif x=='V':
		return 5
	elif x=='X':
		return 10
	elif x=='L':
		return 50
	elif x=='C':
		return 100
	elif x=='D':
		return 500
	elif x=='M':
		return 1000




while True:
	try:
		s=0
		string=input()
		for i in range(len(string)):
			tmp_now =Roman_numerals(string[i:i+1])
			tmp_next=Roman_numerals(string[i+1:i+2])
			if (tmp_now==1 and tmp_next==5):
				s+=-1
			elif (tmp_now==1 and tmp_next==10):
				s+=-1
			elif (tmp_now==10 and tmp_next==50):
				s+=-10
			elif (tmp_now==10 and tmp_next==100):
				s+=-10
			elif (tmp_now==100 and tmp_next==500):
				s+=-100
			elif (tmp_now==100 and tmp_next==1000):
				s+=-100
			else:
				s+=tmp_now
		print(s)

	except EOFError:
		break

Submission status: Accepted

Solution code:
#encoding=utf-8
import sys

def inp():
    for line in sys.stdin:
        word = line.split()
        je(word[0])

def je(word):
    ans, i = 0, 0
    while True:
        if word[i] == "M":
            ans += 1000
        elif word[i] == "D":
            ans += 500
        elif word[i] == "C":
            ans += 100
            try:
                if word[i + 1] == "M":
                    ans += 800
                    i += 1
                elif word[i + 1] == "D":
                    ans += 300
                    i += 1
            except: pass

        elif word[i] == "L":
            ans += 50
        elif word[i] == "X":
            ans += 10
            try:
                if word[i + 1] == "C":
                    ans += 80
                    i += 1
                elif word[i + 1] == "L":
                    ans += 30
                    i += 1
            except: pass

        elif word[i] == "V":
            ans += 5
        elif word[i] == "I":
            ans += 1
            try:
                if word[i + 1] == "X":
                    ans += 8
                    i += 1
                elif word[i + 1] == "V":
                    ans += 3
                    i += 1
            except: pass

        i += 1
        if i == len(word):
            print ans
            break

if __name__ == "__main__":
    inp()

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys

rom = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
for line in sys.stdin:
    ans = 0
    for i in range(len(line)-2):
        if rom[line[i]] < rom[line[i+1]]:
            ans -= rom[line[i]]
        else:
            ans += rom[line[i]]
    ans += rom[line[len(line)-2]]
    print ans

Submission status: Accepted

Solution code:
import sys
for line in sys.stdin:
    roman = list(line)
    roman.pop()
    for i in range(len(roman)):
        if roman[i] == 'I':
            roman[i] = 1
        elif roman[i] == 'V':
            roman[i] = 5
        elif roman[i] == 'X':
            roman[i] = 10
        elif roman[i] == 'L':
            roman[i] = 50
        elif roman[i] == 'C':
            roman[i] = 100
        elif roman[i] == 'D':
            roman[i] = 500
        elif roman[i] == 'M':
            roman[i] = 1000
    x = 0
    for i in range(len(roman)):
        if i == len(roman) - 1:
            x += roman[i]
        elif roman[i] < roman[i+1]:
            x -= roman[i]
        else:
            x += roman[i]
        
    print(x)

Submission status: Accepted

Solution code:
import sys

h = {'I' : 1, 'V' : 5, 'X' : 10, 'L' : 50, 'C' : 100, 'D' : 500, 'M' : 1000, 'E' : 0}

for line in sys.stdin:
	line = line.rstrip()
	line += 'E'
	ans = 0
	i = 0
	while i < len(line) - 1:
		if h[line[i]] >= h[line[i+1]]:
			ans += h[line[i]]
		else:
			ans += h[line[i+1]] - h[line[i]]
			i += 1
		i += 1
	print(ans)

Submission status: Accepted

Solution code:
M = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}

try:
    while 1:
        l = input()

        stock = []
        res = 0
        for v in l:
            if len(stock) == 0 or stock[-1] >= M[v]:
                stock.append(M[v])
            else:
                stock[-1] = M[v] - stock[-1]
                res += sum(stock)
                stock = []

        res += sum(stock)

        print(res)
except:
    pass

Submission status: Accepted

Solution code:
dic = dict(I=1, V=5, X=10, L=50, C=100, D=500, M=1000)
while True:
    try:
        nums = list(map(lambda x: dic[x], list(input())))
    except:
        break
    ans = 0
    for i in range(1, len(nums)):
        if nums[i - 1] >= nums[i]:
            ans += nums[i - 1]
        else:
            ans -= nums[i - 1]
    print(ans + nums[-1])

Submission status: Accepted

Solution code:
import sys

d = {"I":1, "V":5, "X":10, "L":50, "C":100 ,"D":500,"M":1000}
for line in sys.stdin:
  l = [d[i] for i in line.rstrip()]
  if len(l) == 1:
    print(l[0])
  else:
    s = sum(l)
    for i in range(len(l)-1):
      if l[i] < l[i+1]:
        s -= (2*l[i])
    print(s)

Submission status: Accepted

Solution code:
while True:
    try:
        Roma = input()
        Roma = Roma.replace('IV', 'IIII')
        Roma = Roma.replace('IX', 'VIIII')
        Roma = Roma.replace('XL', 'XXXX')
        Roma = Roma.replace('XC', 'LXXXX')
        Roma = Roma.replace('CD', 'CCCC')
        Roma = Roma.replace('CM', 'DCCCC')
        Roma = list(Roma)
        Num = 1000 * Roma.count('M') + 500 * Roma.count('D') + 100 * Roma.count('C') + 50 * Roma.count('L') + 10 * Roma.count('X') + 5 * Roma.count('V') + Roma.count('I')
        print(Num)
        
    except EOFError:
        break

Submission status: Accepted

Solution code:
import sys


def decode_roman_number(data):
    """ ???????????°????????¢????????¢??°??????????????????
    ????????§??????????????¨????????????????????§???I, V, X??????????????????????????????????????¢????????¢??°???????????????????????????

    ?????¬????????????????????????????????????????????????????????????????????????????????§???????????°??????????????¨???????????¨???????????§????????????????????????????????????????????????
    ?¬??????????????????????????°????????????£?????????????????§????????°(???: V ??? I)??????????????????????????§????????°??????????????¨??¨?????????????????????
    ??????????????§???????????£?????????????????§????????°(???: I ??? V)??????????????????????????§????????°??????????????¨??¨?????????????????????
    ???????????????????????°??????????¬????????????¨????????????????????????????????????
    ??¨???????????????????????????????????????????????£????????????????????¨???????????¨???
    """
    numbers = []
    for d in data:
        if d == 'I':
            numbers.append(1)
        elif d == 'V':
            numbers.append(5)
        elif d == 'X':
            numbers.append(10)
        elif d == 'L':
            numbers.append(50)
        elif d == 'C':
            numbers.append(100)
        elif d == 'D':
            numbers.append(500)
        elif d == 'M':
            numbers.append(1000)
        else:
            raise ValueError

    decoded_number = 0  # ??¢????????¢??°??????????????????????????????
    my_stack = []
    for n in numbers:
        if len(my_stack) == 0:  # ???????????????????????????????????§??????????????§?????¨?????????????????????????????????
            my_stack.append(n)
        else:
            while len(my_stack) > 0 and my_stack[-1] < n:  # I???V ??? X???C ??????????????±?????????????????¨
                decoded_number -= my_stack.pop()
            while len(my_stack) > 0:
                decoded_number += my_stack.pop()
            my_stack.append(n)  # ???????????????????¬????????????¨??????????????????????????§??????????????????????????¨???XXIV(24)???????????£????????????????????§????????????
    while len(my_stack) > 0:
        decoded_number += my_stack.pop()
    return decoded_number


if __name__ == '__main__':
    #
    for line in sys.stdin:
        data = line.strip()
        # data = 'CCCCLXXXXVIIII'
        # data = 'MCMXLV'

        # ???????????°???????§£???
        ans = decode_roman_number(data)

        # ???????????¨???
        print(ans)

Submission status: Accepted

Solution code:
import sys


def decode_roman_number(data):
    """ ???????????°????????¢????????¢??°??????????????????
    ????????§??????????????¨????????????????????§???I, V, X??????????????????????????????????????¢????????¢??°???????????????????????????

    ?????¬????????????????????????????????????????????????????????????????????????????????§???????????°??????????????¨???????????¨???????????§????????????????????????????????????????????????
    ?¬??????????????????????????°????????????£?????????????????§????????°(???: V ??? I)??????????????????????????§????????°??????????????¨??¨?????????????????????
    ??????????????§???????????£?????????????????§????????°(???: I ??? V)??????????????????????????§????????°??????????????¨??¨?????????????????????
    ???????????????????????°??????????¬????????????¨????????????????????????????????????
    ??¨???????????????????????????????????????????????£????????????????????¨???????????¨???
    """
    roman_num = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}  # ???????????°???????????????????????????????????????

    decoded_number = 0  # ??¢????????¢??°??????????????????????????????
    my_stack = []
    for c in data:
        try:
            if len(my_stack) == 0:  # ???????????????????????????????????§??????????????§?????¨?????????????????????????????????
                my_stack.append(c)
            else:
                while len(my_stack) > 0 and roman_num[my_stack[-1]] < roman_num[c]:  # I???V ??? X???C ??????????????±?????????????????¨
                    decoded_number -= roman_num[my_stack.pop()]
                while len(my_stack) > 0:
                    decoded_number += roman_num[my_stack.pop()]
                my_stack.append(c)  # ???????????????????¬????????????¨??????????????????????????§??????????????????????????¨???XXIV(24)???????????£????????????????????§????????????
        except KeyError:
            raise ValueError
    while len(my_stack) > 0:
        try:
            decoded_number += roman_num[my_stack.pop()]
        except KeyError:
            raise ValueError
    return decoded_number


if __name__ == '__main__':
    #
    for line in sys.stdin:
        data = line.strip()
        # data = 'CCCCLXXXXVIIII'
        # data = 'MCMXLV'

        # ???????????°???????§£???
        ans = decode_roman_number(data)

        # ???????????¨???
        print(ans)

Submission status: Accepted

Solution code:
nums={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
while True:
    try:
        s=input()
    except:
        break
    ans=nums[s[0]]
    for i in range(1,len(s)):
        if nums[s[i-1]]<nums[s[i]]:
            ans+=nums[s[i]]-2*nums[s[i-1]]
        else:
            ans+=nums[s[i]]
    print(ans)

Submission status: Accepted

Solution code:
nums={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
while True:
    try:
        s=input()
    except:
        break
    ans=nums[s[0]]
    for i in range(1,len(s)):
        if nums[s[i-1]]<nums[s[i]]:
            ans-=2*nums[s[i-1]]
        ans+=nums[s[i]]
    print(ans)

Submission status: Accepted

Solution code:
val={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
rom=['I','V','X','L','C','D','M']
while True:
    try:
        s = list(input().strip())
        w = 0
        c = s[0]
        s = s[1:]
        while len(s) > 0:
            if rom.index(s[0]) <= rom.index(c):
                w += val[c]
            else:
                w -= val[c]
            c = s[0]
            s = s[1:]

        w += val[c]
        print(w)

    except EOFError:
        break

Submission status: Accepted

Solution code:
num = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}

while True:
    try:
        S = input()
    except EOFError:
        break
    ans = 0
    for i in range(0,len(S) - 1):
        if num [S [i]] < num [S [i + 1]]:
            ans -= num [S [i]]
        else:
            ans += num [S [i]]
    ans += num [S [-1]]
    print(ans)

Submission status: Accepted

Solution code:
rule = ["I","V","X","L","C","D","M"]
val = [1,5,10,50,100,500,1000]
while True:
    try:
        nums = input()
        ans = val[rule.index(nums[0])]

        for i in range(1,len(nums)):
            ans += val[rule.index(nums[i])]
            if rule.index(nums[i]) > rule.index(nums[i-1]):
                ans -= (2*val[rule.index(nums[i-1])])

        print(ans)
    except EOFError: break

Submission status: Accepted

Solution code:
# -*- coding: utf-8 -*-

import sys
import os


alab = {}
alab['I'] = 1
alab['V'] = 5
alab['X'] = 10
alab['L'] = 50
alab['C'] = 100
alab['D'] = 500
alab['M'] = 1000

for s in sys.stdin:
    s = s.strip()
    #print('s', s)

    A = []
    for c in s:
        A.append(alab[c])
    #print('A', A)

    for i in range(len(A) - 1):
        if A[i] < A[i+1]:
            A[i] *= -1
    #print('A', A)

    print(sum(A))

Submission status: Accepted

Solution code:
sample = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M':1000}
while True :
    try :
        temp = input()
        f = temp[0]
        total = 0 
        for _ in temp[1:] :
            if sample[f] < sample[_] : total -= sample[f]
            else : total += sample[f]
            f = _
        total += sample[temp[-1]]
        print(total)
    except : break

Submission status: Accepted

Solution code:
figures = ["M", "D", "C", "L", "X", "V", "I"]
hoge = {0: 1000, 1: 500, 2: 100, 3: 50, 4: 10, 5: 5, 6: 1}

while True:
    try:
        st = input()
    except:
        break
    idx = figures.index(st[0])
    res = [hoge[idx]]
    pretoken = st[0]
    for i, s in enumerate(st[1:]):
        idx = figures.index(s)
        preidx = figures.index(pretoken)
        if idx < preidx:
            res[i] = -1 * res[i]
        res.append(hoge[idx])
        pretoken = s
    print(sum(res))

Submission status: Accepted

Solution code:
import sys


def arabic(s):
    if s == "I":
        return 1
    elif s == "V":
        return 5
    elif s == "X":
        return 10
    elif s == "L":
        return 50
    elif s == "C":
        return 100
    elif s == "D":
        return 500
    elif s == "M":
        return 1000
    else:
        return -1


for i in sys.stdin:
    S = 0
    for j in range(len(i)):
        if arabic(i[j]) == -1:
            continue
            # print("ver1")
        elif j != 0 and arabic(i[j-1]) < arabic(i[j]):
                S = S - arabic(i[j-1]) * 2 + arabic(i[j])
                # print("ver2")
        else:
            S += arabic(i[j])
            # print("ver3")
        # print(str(S) + "!")
    print(S)

Submission status: Accepted

Solution code:
# Aizu Problem 0039: Roman Figure
#
import sys, math, os

# read input:
PYDEV = os.environ.get('PYDEV')
if PYDEV=="True":
    sys.stdin = open("sample-input.txt", "rt")


def roman_to_decimal(r):
    n = 0
    while len(r) > 0 and r[0] == "M":
        n += 1000
        r = r[1:]
    if len(r) == 0:
        return n
    if r[:2] == "CM":
        n += 900
        r = r[2:]
    if len(r) == 0:
        return n
    if r[0] == "D":
        n += 500
        r = r[1:]
    if len(r) == 0:
        return n
    if r[:2] == "CD":
        n += 400
        r = r[2:]
    if len(r) == 0:
        return n
    while len(r) > 0 and r[0] == "C":
        n += 100
        r = r[1:]
    if len(r) == 0:
        return n
    if r[:2] == "XC":
        n += 90
        r = r[2:]
    if len(r) == 0:
        return n
    if r[0] == "L":
        n += 50
        r = r[1:]
    if len(r) == 0:
        return n
    if r[:2] == "XL":
        n += 40
        r = r[2:]
    if len(r) == 0:
        return n
    while len(r) > 0 and r[0] == "X":
        n += 10
        r = r[1:]
        if len(r) == 0:
            return n
    if r[:2] == "IX":
        n += 9
    elif r[:2] == "IV":
        n += 4
    else:
        if r[0] == "V":
            n += 5
            r = r[1:]
        while len(r) > 0 and r[0] == "I":
            n += 1
            r = r[1:]
            if len(r) == 0:
                return n
    return n

for line in sys.stdin:
    print(roman_to_decimal(line.strip()))

Submission status: Accepted

Solution code:
import sys

roman = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}


def check(i, y):
  if i == y:
    return True
  elif i == 'I' and y == 'V':
    return True
  elif i == 'V' and (y == 'I' or y == 'X'):
    return True
  elif i == 'X' and (y == 'V' or y == 'L'):
    return True
  elif i == 'L' and (y == 'X' or y == 'C'):
    return True
  elif i == 'C' and (y == 'L' or y == 'D'):
    return True
  elif i == 'D' and (y == 'C' or y == 'M'):
    return True
  elif i == 'M' and y == 'D':
    return True
  else:
    return False


def solve(r):
  if len(r) == 1:
    return roman[r[0]]
  else:
    maxRoman = 0
    for i in range(len(r) - 1):
      if roman[r[i]] < roman[r[i + 1]]:
        maxRoman = i + 1
      else:
        break
    ans = roman[r[maxRoman]]
    for sub in range(maxRoman - 1, -1, -1):
      ans -= roman[r[sub]]
    for add in range(maxRoman + 1, len(r)):
      if add < len(r) - 1 and not check(r[add - 1], r[add]):
        r = r[add:]
        return ans + solve(r)
      ans += roman[r[add]]
  return ans


for line in sys.stdin:
  try:
    line = line.replace('\n', '')
    print(solve(line))
  except:
    break

Submission status: Accepted

Solution code:
import sys

d = {
    'I': 1,
    'V': 5,
    'X': 10,
    'L': 50,
    'C': 100,
    'D': 500,
    'M': 1000
}

for s in sys.stdin:
    c = 0
    for i,j in enumerate(list(s)):
        if j == '\n':
            break
        try:
            if j == 'I' and (s[i+1] == 'V' or s[i+1] == 'X'):
                c -= 1
            elif j == 'X' and (s[i+1] == 'L' or s[i+1] == 'C'):
                c -= 10
            elif j == 'C' and (s[i+1] == 'D' or s[i+1] == 'M'):
                c -= 100
            else:
                c += d[j]
        except:
            c += d[j]
    print(c)

Submission status: Accepted

Solution code:
r_dict = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
while True:
    try:
        s = 0
        b = 0
        r = input()
        for i in range(len(r))[::-1]:
            a = r_dict[r[i]]
            if b <= a:
                s += a
            else:
                s -= a
            b = a
        print(s)
    except:
        break

Submission status: Accepted

Solution code:
def get_input():
    while True:
        try:
            yield ''.join(input())
        except EOFError:
            break

N = list(get_input())

for l in range(len(N)):
    num = N[l]
    ans = 0
    d = 0
    d_past = 9999
    for i in range(len(num)):
        if num[i] == "I":
            d = 1
        elif num[i] == "V":
            d = 5
        elif num[i] == "X":
            d = 10
        elif num[i] == "L":
            d = 50
        elif num[i] == "C":
            d = 100
        elif num[i] == "D":
            d = 500
        elif num[i] == "M":
            d = 1000

        if d_past < d:
            ans -= d_past * 2

        ans += d
        d_past = d
    print(ans)

Submission status: Accepted

Solution code:
r={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
import sys
for e in sys.stdin:
 a=0
 n=[r[c]for c in e.strip()]
 for i in range(len(n)):
  if i+1<len(n)and n[i]<n[i+1]:a-=n[i]
  else:a+=n[i]
 print(a)

Submission status: Accepted

Solution code:
import sys
r={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for e in sys.stdin:
 a=0
 n=[r[c]for c in e.strip()]
 for i in range(len(n)):
  if i+1<len(n)and n[i]<n[i+1]:a-=n[i]
  else:a+=n[i]
 print(a)

Submission status: Accepted

Solution code:
import sys
r={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for e in sys.stdin:
 n=[r[c]for c in e.strip()]
 print(sum(n[i]*[1,-1][i+1<len(n)and n[i]<n[i+1]]for i in range(len(n))))

Submission status: Accepted

Solution code:
import sys
r={'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
for e in sys.stdin:
 n=[r[c]for c in e[:-1]]
 print(sum(n[i]*[1,-1][i+1<len(n)and n[i]<n[i+1]]for i in range(len(n))))

Submission status: Accepted

Solution code:
dic = {"I":1, "V":5, "X":10, "L":50, "C":100 ,"D":500,"M":1000}

while True:
  try:
    line = [dic[i] for i in input()]
    acc = 0

    for i in range(len(line) - 1):
      if line[i] < line[i + 1]:
        acc -= line[i]
      else:
        acc += line[i]

    acc += line[-1]
    print(acc)

  except EOFError:
    break

Submission status: Accepted

Solution code:
import sys
r_d={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
res=[]
for s in sys.stdin:
    l=[r_d[i] for i in s.strip()]
    m=[l[i] if l[i]>=l[i+1] else -l[i] for i in range(len(l)-1)]
    m.extend([l[-1]])
    res.extend([sum(m)])
[print(i) for i in res]

Submission status: Accepted

Solution code:
# AOJ 0039 Roman Figure
# Python3 2018.6.15 bal4u

roman = {'I':1, 'V':5, 'X':10, 'L':50, 'C':100, 'D':500, 'M': 1000}

while True:
	try:
		p = list(input())
	except EOFError:
		break
	ans = i = 0
	while i < len(p):
		if i+1 < len(p) and roman[p[i]] < roman[p[i+1]]:
			ans += roman[p[i+1]] - roman[p[i]]
			i += 1
		else: ans += roman[p[i]]
		i += 1
	print(ans)

Submission status: Accepted

Solution code:
table = {"I": 1, "V": 5, "X": 10, "L": 50, "C": 100, "D": 500, "M": 1000}

try:
    while True:
        a = [table[c] for c in input()] + [0]
        result = 0
        for n1, n2 in zip(a, a[1:]):
            result += n1 if n1 >= n2 else -n1

        print(result)

except EOFError:
    exit()

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# coding: utf-8

import sys


def parseRomanNumber(roman):
    roman_dict = {
      "I": 1,
      "V": 5,
      "X": 10,
      "L": 50,
      "C": 100,
      "D": 500,
      "M": 1000}
    numbers = [0]
    roman = roman.replace("\n", "")
    for i in [roman_dict[c] for c in roman[::-1]]:
        if i >= numbers[-1]:
            numbers.append(i)
        else:
            numbers.append(i * -1)
    return sum(numbers)


def main():
    romans = sys.stdin.readlines()
    for roman in romans:
        print parseRomanNumber(roman)


if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:
import sys
dic={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
for line in sys.stdin.readlines():
    total,temp,left=0,0,line[0]
    for roman in line:
        if left==roman:
            temp+=dic[roman]
        else:
            if roman=="\n":
                total+=temp
                break
            if dic[left]>dic[roman]:
                total+=temp
            else:
                  total-=temp
            left=roman
            temp=dic[roman]
    print total

Submission status: Accepted

Solution code:
rule = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

while True:
    try:
        line = raw_input()
        nums = [rule[c] for c in list(line)] + [0]
        print sum(map(
            lambda (a, b): -a if a < b else a,
            [(a, b) for a, b in [nums[i:i+2] for i in range(len(line))]]))

    except EOFError:
        break

Submission status: Accepted

Solution code:
d={"I":1,"V":5,"X":10,"L":50,"C":100,"D":500,"M":1000}
while True:
    try:
        s=[d[i] for i in raw_input()]
    except EOFError:
        break
    i,m=0,0
    while i<len(s)-1:
        if s[i]<s[i+1]:
            m+=s[i+1]-s[i]
            s[i],s[i+1]=0,0
            i+=2
        else:
            i+=1
    print sum(s)+m

Submission status: Accepted

Solution code:

import sys


def solv(roman):
    a = map(lambda x: roman_to_arabic(x), roman)
    arabic = reduce(roman_count, a, (0,0))[0]
    return arabic

def roman_to_arabic(s):
    tbl = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}
    return tbl[s]

def roman_count(acc, y):
    x = acc[1]
    if x < y:
       a = acc[0] + y - 2 * x
    else:
       a = acc[0] + y
    return (a, y)


for line in sys.stdin:
    roman = line.rstrip("\n")
    print solv(roman)

Submission status: Accepted

Solution code:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import (division, absolute_import, print_function,
                        unicode_literals)

from sys import stdin
from re import findall

FIGURE = {'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000}

for line in stdin:
    vs = [FIGURE[s[0]] * len(s) for s in findall('(\w)\1*', line)]
    value = 0
    while vs:
        buf = vs.pop(0)
        if vs and buf < vs[0]:
            value -= buf
        else:
            value += buf
    print(value)