Problem:


Problem C: Numeral System

Prof. Hachioji has devised a new numeral system of
integral numbers with four lowercase letters "m", "c", "x", "i"
and with eight digits "2", "3", "4", "5", "6", "7", "8", "9". 
He doesn't use digit "0" nor digit "1" in this system.

The letters "m", "c", "x" and "i" correspond to 1000, 100, 10 and 1,
respectively, 
and the digits "2", ...,"9" correspond to 2, ..., 9, respectively.
This system has  nothing to do with the Roman numeral system.

For example,
character strings

    "5m2c3x4i", "m2c4i"  and   "5m2c3x"

correspond to the integral numbers 
5234 (=5*1000+2*100+3*10+4*1),
1204 (=1000+2*100+4*1),
 and 5230 (=5*1000+2*100+3*10), 
respectively.  
The parts of strings in the above example, "5m", "2c", "3x" and "4i" 
represent 5000 (=5*1000), 200 (=2*100), 30 (=3*10) and 4 (=4*1),
respectively. 

Each of the letters "m", "c", "x" and "i" may
 be prefixed by one of the digits
"2", "3", ..., "9". 
In that case, the prefix digit and the letter are regarded 
as a pair.
A pair that consists of a prefix digit and a letter 
corresponds to an integer that is equal to
the original value of the letter multiplied by 
the value of the prefix digit.

For each letter "m", "c", "x" and "i", 
the number of its occurrence in a string is at most one.
When it has a prefix digit, it should appear together with the prefix digit.
The letters "m", "c", "x" and "i" must appear in this order, from left to right.
Moreover, when a digit exists in a string,
it should appear as the prefix digit of the following letter.
Each letter may be omitted in a string, but
the whole string must not be empty.
A string made in this manner is called an MCXI-string.

An MCXI-string corresponds to a positive integer 
that is the sum of the values of the letters
and those of the pairs contained in it as mentioned above. 
The positive integer corresponding to an MCXI-string is called its
MCXI-value.
Moreover, given an integer from 1 to 9999,
there is a unique MCXI-string whose MCXI-value is equal 
to the given integer.
For example,
the MCXI-value of an MCXI-string "m2c4i" is 
1204 that is equal to 1000 + 2*100 + 4*1.
There are no MCXI-strings but "m2c4i" that correspond to 1204.
Note
that strings "1m2c4i", "mcc4i", "m2c0x4i", and "2cm4i" are
not valid MCXI-strings. 
The reasons are use of "1",
multiple occurrences of "c", use of "0", and the wrong order of "c" and "m",
respectively.

Your job is to write a program for Prof. Hachioji
that reads two MCXI-strings, 
computes the sum of their MCXI-values, and
prints the MCXI-string corresponding to the result.

Input

The input is as follows.
The first line contains a positive integer n (k+1 th line is the specification of 
the k th computation (k=1, ..., n).

n                                    

specification1            

specification2            

    ...
                   
specificationn     

Each specification is described in a line:

MCXI-string1 MCXI-string2

The two MCXI-strings are separated by a space.

You may assume that the sum of the two MCXI-values 
of the two MCXI-strings in each specification 
is less than or equal to 9999. 

Output

For each specification,
your program should print an MCXI-string in a line.
Its MCXI-value should be the sum of the two MCXI-values
of the MCXI-strings in the specification.
No other characters should appear in the output.

Sample Input

10
xi x9i
i 9i
c2x2i 4c8x8i
m2ci 4m7c9x8i
9c9x9i i
i 9m9c9x8i
m i
i m
m9i i
9m8c7xi c2x8i

Output for the Sample Input

3x
x
6cx
5m9c9x9i
m
9m9c9x9i
mi
mi
mx
9m9c9x9i



Sample input:
10
xi x9i
i 9i
c2x2i 4c8x8i
m2ci 4m7c9x8i
9c9x9i i
i 9m9c9x8i
m i
i m
m9i i
9m8c7xi c2x8i


Sample output:
3x
x
6cx
5m9c9x9i
m
9m9c9x9i
mi
mi
mx
9m9c9x9i

Submission status: Wrong Answer

Solution code:
ans_list = []
n = int(input())

def mcxl2digit(s):
    ans = 0
    dig = 1
    for i in range(len(s)):
        if "2" <= s[i] <= "9":
            dig = int(s[i])
        else:
            if s[i] == "m":
                key = 100
            elif s[i] == "c":
                key = 100
            elif s[i] == "x":
                key = 10
            else:
                key = 1
            ans += key * dig
            dig = 1
    return ans

def digit2mcxl(i):
    return_list = []
    m = i // 1000
    if m != 0 and m != 1:
        return_list.append(str(m))
    if m != 0:
        return_list.append("m")
    i = i % 1000

    c = i // 100
    if c != 0 and c != 1:
        return_list.append(str(c))
    if c != 0:
        return_list.append("c")
    i = i % 100

    x = i // 10
    if x != 0 and x != 1:
        return_list.append(str(x))
    if x != 0:
        return_list.append("x")
    i = i % 10

    l = i
    if l != 0 and l != 1:
        return_list.append(str(l))
    if l != 0:
        return_list.append("l")

    return return_list

for i in range(n):
    a, b = input().split()
    ans = (mcxl2digit(a) + mcxl2digit(b))
    ans = digit2mcxl(ans)
    ans_list.append(ans)
for i in ans_list:
    print("".join(i))

Submission status: Wrong Answer

Solution code:
ans_list = []
n = int(input())

def mcxl2digit(s):
    ans = 0
    dig = 1
    for i in range(len(s)):
        if "2" <= s[i] <= "9":
            dig = int(s[i])
        else:
            if s[i] == "m":
                key = 1000
            elif s[i] == "c":
                key = 100
            elif s[i] == "x":
                key = 10
            else:
                key = 1
            ans += key * dig
            dig = 1
    return ans

def digit2mcxl(i):
    return_list = []
    m = i // 1000
    if m != 0 and m != 1:
        return_list.append(str(m))
    if m != 0:
        return_list.append("m")
    i = i % 1000

    c = i // 100
    if c != 0 and c != 1:
        return_list.append(str(c))
    if c != 0:
        return_list.append("c")
    i = i % 100

    x = i // 10
    if x != 0 and x != 1:
        return_list.append(str(x))
    if x != 0:
        return_list.append("x")
    i = i % 10

    l = i
    if l != 0 and l != 1:
        return_list.append(str(l))
    if l != 0:
        return_list.append("l")

    return return_list

for i in range(n):
    a, b = input().split()
    ans = (mcxl2digit(a) + mcxl2digit(b))
    #print(a, b, mcxl2digit(a), mcxl2digit(b))
    #print(ans)
    ans = digit2mcxl(ans)
    ans_list.append(ans)
for i in ans_list:
    print("".join(i))

Submission status: Wrong Answer

Solution code:
n=int(input())
for i in range(n):
    s0,s1=map(str,input().split())
    ans=""
    ans0=0
    ans1=0
    ans2=0
    p=1
    for j in range(len(s0)):
        if s0[j]!="m" and s0[j]!="c" and s0[j]!="x" and s0[j]!="i" :
            p=int(s0[j])
            continue
        if s0[j]=="m":
            ans0+=p*1000
            p=1 
        if s0[j]=="c":
            ans0+=p*100
            p=1
        if s0[j]=="x":
            ans0+=p*10
            p=1
        if s0[j]=="i":
            ans0+=p*1
            p=1
    for k in range(len(s1)):
        if s1[k]!="m" and s1[k]!="c" and s1[k]!="x" and s1[k]!="i" :
            p=int(s1[k])
            continue
        if s1[k]=="m":
            ans1+=p*1000 
            p=1
        if s1[k]=="c":
            ans1+=p*100
            p=1
        if s1[k]=="x":
            ans1+=p*10
            p=1
        if s1[k]=="i":
            ans1+=p*1
            p=1
    print(ans0)
    print(ans1)
    ans2=ans0+ans1
    while ans2>0:
        if ans2>=1000:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"m"
            else:
                ans=ans+sans2[0]+"m"
            ans2=int(sans2[1:])
            continue
        if ans2>=100:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"c"
            else:
                ans=ans+sans2[0]+"c"
            ans2=int(sans2[1:])
            continue
        if ans2>=10:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"x"
            else:
                ans=ans+sans2[0]+"x"
            ans2=int(sans2[1:])
            continue
        if ans2>=1:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"i"
            else:
                ans=ans+sans2[0]+"i"
            break
    print(ans)

Submission status: Wrong Answer

Solution code:
import math

n = int(input())

def mcxi2int(s):
    m = {'m': 1000, 'c': 100, 'x': 10, 'i': 1}

    ret = 0
    i = 0
    while i < (len(s)):
        num = 1
        maci = s[i]
        if maci.isdigit():
            num = int(maci)
            maci = s[i + 1]
            i += 1
        ret += num * m[maci]
        i += 1
    return ret


def int2mcxi(n):
    keys = ['m', 'c', 'x', 'i']
    values = [1000, 100, 10, 1]

    ret = ""
    for k, v in zip(keys, values):
        i = math.floor(n / v)
        n = n % v
        if i == 0:
            continue
        elif i == 1:
            ret = ret + k
        else:
            ret = ret + str(i) + k
    print(ret)

for _ in range(n):
    m1, m2 = raw_input().split()
    print int2mcxi(mcxi2int(m1) + mcxi2int(m2))

Submission status: Wrong Answer

Solution code:
import math

n = int(input())

def mcxi2int(s):
    m = {'m': 1000, 'c': 100, 'x': 10, 'i': 1}

    ret = 0
    i = 0
    while i < (len(s)):
        num = 1
        maci = s[i]
        if maci.isdigit():
            num = int(maci)
            maci = s[i + 1]
            i += 1
        ret += num * m[maci]
        i += 1
    return ret


def int2mcxi(n):
    keys = ['m', 'c', 'x', 'i']
    values = [1000, 100, 10, 1]

    ret = ""
    for k, v in zip(keys, values):
        i = math.floor(n / v)
        n = n % v
        if i == 0:
            continue
        elif i == 1:
            ret = ret + k
        else:
            ret = ret + str(i) + k
    return ret

for _ in range(n):
    m1, m2 = raw_input().split()
    print int2mcxi(mcxi2int(m1) + mcxi2int(m2))

Submission status: Wrong Answer

Solution code:
trial = int(input())
numlist = [str(n) for n in range(2,10)]

cases = []
for t in range(trial):
    cases.append(input().split(" "))
print(cases)
for case in range(len(cases)):
    num = 0
    for ba in range(2):
        for n in range(len(cases[case][ba])):
                if cases[case][ba][n] == "m":
                    if n - 1 == 0:
                        num += int(cases[case][ba][n-1]) * 1000
                    else:
                        num += 1000
                elif cases[case][ba][n] == "c":
                    if (n - 1 == 0 and cases[case][ba][n-1] != "m") or cases[case][ba][n-1] in numlist:
                        num += int(cases[case][ba][n-1]) * 100
                    else:
                        num += 100
                elif cases[case][ba][n] == "x":
                    if (n - 1 == 0 and cases[case][ba][n-1] not in ["m","c"]) in numlist:
                        num += int(cases[case][ba][n-1]) * 10
                    else:
                        num += 10
                elif cases[case][ba][n] == "i":
                    if (n - 1 == 0 and cases[case][ba][n-1] not in ["m","c","x"]) or cases[case][ba][n-1] in numlist:
                        num += int(cases[case][ba][n-1]) * 1
                    else:
                        num += 1
    else:
        num = str(num)
        answer = ""
        print(num)
        for n in range(len(num)):
            if len(num) - 1 - n == 3:
                if num[n] == "1":
                    answer += "m"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "m"
            if len(num) - 1 - n == 2:
                if num[n] == "1":
                    answer += "c"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "c"
            if len(num) - 1 - n == 1:
                if num[n] == "1":
                    answer += "x"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "x"
            if len(num) - 1 - n == 0:
                if num[n] == "1":
                    answer += "i"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "i"
        else:
            print(answer)

Submission status: Wrong Answer

Solution code:
a={'m':1000,'c':100,'x':10,'i':1}
for _ in range(int(input())):
    b,s,t=input(),0,1
    for x in b:
        if x==' ':continue
        if x in a:s+=a[x]*t;t=1
        else:t=int(x)
    ans=''
    for k in ['m','c','x','i']:
        c,s=divmod(s,a[k])
        if c:ans+=['',str(c)][c!=0]+k
    print(ans)

Submission status: Wrong Answer

Solution code:
def mcxiToDigit(s):
    s="1"+s
    num=0
    dic={"m":1000,"c":100,"x":10,"i":1}
    for c in dic:
        if c in s:
            if "2"<=s[s.index(c)-1]<="9":
                num+=int(s[s.index(c)-1])*dic[c]
            else:
                num+=dic[c]
    return num

for i in range(input()):
    L=raw_input().split()
    sm=mcxiToDigit(L[0])+mcxiToDigit(L[1])
    print sm
    T=((1000,"m"),(100,"c"),(10,"x"),(1,"i"))
    s=""
    for d,c in T:
        val=sm/d
        if val>1:
            s+=str(val)+c
        elif val==1:
            s+=c
        sm%=d
    print s

Submission status: Accepted

Solution code:
def get10(x):
    ans =0
    alphabet = {'m':1000,'c':100,'x':10,'i':1}
    i =0
    while i < len(x):
        if not x[i] in alphabet:
            ans += int(x[i])*alphabet[x[i+1]]
            i +=2
        elif x[i] in alphabet:
            ans +=alphabet[x[i]]
            i+=1
    return ans

def getN(x):
    ans =[]
    temp = x
    while temp !=0:
        if temp//1000:
            if temp//1000 == 1: ans.append('m')
            else:
                ans.append(str(temp//1000)+'m')
            temp = temp%1000
        elif temp//100:
            if temp//100 == 1: ans.append('c')
            else:
                ans.append(str(temp//100)+'c')
            temp = temp%100
        elif temp//10:
            if temp//10 == 1: ans.append('x')
            else:
                ans.append(str(temp//10)+'x')
            temp = temp%10
        else:
            if temp == 1:ans.append('i')
            elif temp >0:
                ans.append(str(temp)+'i')
            temp = temp//10
        
    
    return  ''.join(ans)



n = int(input())
for _ in range(n):
    x,y = input().split(' ')
    temp =get10(x) + get10(y)
    print(getN(temp))

Submission status: Accepted

Solution code:
ans_list = []
n = int(input())

def mcxl2digit(s):
    ans = 0
    dig = 1
    for i in range(len(s)):
        if "2" <= s[i] <= "9":
            dig = int(s[i])
        else:
            if s[i] == "m":
                key = 1000
            elif s[i] == "c":
                key = 100
            elif s[i] == "x":
                key = 10
            else:
                key = 1
            ans += key * dig
            dig = 1
    return ans

def digit2mcxl(i):
    return_list = []
    m = i // 1000
    if m != 0 and m != 1:
        return_list.append(str(m))
    if m != 0:
        return_list.append("m")
    i = i % 1000

    c = i // 100
    if c != 0 and c != 1:
        return_list.append(str(c))
    if c != 0:
        return_list.append("c")
    i = i % 100

    x = i // 10
    if x != 0 and x != 1:
        return_list.append(str(x))
    if x != 0:
        return_list.append("x")
    i = i % 10

    l = i
    if l != 0 and l != 1:
        return_list.append(str(l))
    if l != 0:
        return_list.append("i")

    return return_list

for i in range(n):
    a, b = input().split()
    ans = (mcxl2digit(a) + mcxl2digit(b))
    #print(a, b, mcxl2digit(a), mcxl2digit(b))
    #print(ans)
    ans = digit2mcxl(ans)
    ans_list.append(ans)
for i in ans_list:
    print("".join(i))

Submission status: Accepted

Solution code:
n=int(input())
for i in range(n):
    s0,s1=map(str,input().split())
    ans=""
    ans0=0
    ans1=0
    ans2=0
    p=1
    for j in range(len(s0)):
        if s0[j]!="m" and s0[j]!="c" and s0[j]!="x" and s0[j]!="i" :
            p=int(s0[j])
            continue
        if s0[j]=="m":
            ans0+=p*1000
            p=1 
        if s0[j]=="c":
            ans0+=p*100
            p=1
        if s0[j]=="x":
            ans0+=p*10
            p=1
        if s0[j]=="i":
            ans0+=p*1
            p=1
    for k in range(len(s1)):
        if s1[k]!="m" and s1[k]!="c" and s1[k]!="x" and s1[k]!="i" :
            p=int(s1[k])
            continue
        if s1[k]=="m":
            ans1+=p*1000 
            p=1
        if s1[k]=="c":
            ans1+=p*100
            p=1
        if s1[k]=="x":
            ans1+=p*10
            p=1
        if s1[k]=="i":
            ans1+=p*1
            p=1
    ans2=ans0+ans1
    while ans2>0:
        if ans2>=1000:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"m"
            else:
                ans=ans+sans2[0]+"m"
            ans2=int(sans2[1:])
            continue
        if ans2>=100:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"c"
            else:
                ans=ans+sans2[0]+"c"
            ans2=int(sans2[1:])
            continue
        if ans2>=10:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"x"
            else:
                ans=ans+sans2[0]+"x"
            ans2=int(sans2[1:])
            continue
        if ans2>=1:
            sans2=str(ans2)
            if sans2[0]=="1":
                ans=ans+"i"
            else:
                ans=ans+sans2[0]+"i"
            break
    print(ans)

Submission status: Accepted

Solution code:
p = {
    'm': 1000,
    'c': 100,
    'x': 10,
    'i': 1,
}

def parseNum(s):
    if s[0].isdigit():
        return int(s[0]), s[1:]
    return 1, s

def parseChar(s):
    if s[0] in p:
        return p[s[0]], s[1:]
    print(s)

def parseMCXI(s):
    res = 0
    while s:
        x, s = parseNum(s)
        w, s = parseChar(s)
        res += x * w
    return res

def to(x):
    if x == 0: return None
    if x == 1: return ""
    return str(x)

def toMCXI(x):
    res = ""
    for w, c in sorted(zip(p.values(), p.keys()), reverse=True):
        s = to(x // w)
        if s is not None:
            res += s + c
            x = x % w
    return res
for _ in range(int(input())):
    print(toMCXI(sum(parseMCXI(x) for x in input().split())))

Submission status: Accepted

Solution code:
W = {'m':1000,'c':100,'x':10,'i':1}
K = ['m','c','x','i']
for i in range(int(input())):
    x = input()
    tmp = 1
    r = 0
    for w in list(x):
        if w == ' ':continue
        if w in K:
            r += W[w] * tmp
            tmp = 1
        else:
            tmp = int(w)

    div = 1000
    res = ''
    for i in range(4):
        d,r = divmod(r,div)
        if d > 0:
            res += ('' if d == 1 else str(int(d))) + K[i]
        div /= 10

    print(res)

Submission status: Accepted

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

mcxi = {'m' : 1000,'c' : 100, 'x': 10, 'i': 1}
mcxi_inv = dict(zip(mcxi.values(),mcxi.keys()))
def mcxi2num(text):
    num = 0
    n = 1
    for i in text:
        if i.isnumeric():
            n = int(i)
        else:
            num += n * mcxi[i]
            n = 1
    return num

n = int(input())
for i in range(n):
    a,b = input().split()
    num = mcxi2num(a)+mcxi2num(b)
    ans = ''
    for n in list(reversed(sorted(mcxi.values()))):
        ans += str(num // n) if num // n != 0 and num // n != 1 else ''
        ans += mcxi_inv[n] if num // n != 0 else ''
        num -= n * (num // n)
    print(ans)

Submission status: Accepted

Solution code:
def mcxi2num (mcxi):
	changer = {"m":1000, "c":100, "x":10, "i":1}
	num = 0
	prefix = 1
	for s in mcxi:
		if s in "mcxi":
			num += prefix * changer[s]
			prefix = 1
		else :
			prefix = int(s)
	return num

def num2mcxi (num):
	changer = ["i", "x", "c", "m"]
	mcxi = ""
	numstr = str(num)
	length = len(numstr)
	for i in range(length):
		if numstr[i] == "0":
			pass
		elif numstr[i] == "1":
			mcxi += changer[length-i-1]
		else:
			mcxi += numstr[i] + changer[length-i-1]
	return mcxi

n = int(raw_input())
for i in range(n):
	s1, s2 = raw_input().split(" ")
	print num2mcxi(mcxi2num(s1) + mcxi2num(s2))

Submission status: Accepted

Solution code:
def encode(n):
    ns = []
    mcxi = ['m','c','x','i']
    v = 1000
    for i in range(4):
        m = 0
        while n >= v:
            n -= v
            m += 1
        v = int(v/10)
        if m > 0:
            ns.append(str(m)+mcxi[i])
    return ''.join(ns).replace('1','')

def decode(s):
    coe = 1
    n = 0
    for c in s:
        if c in map(str, range(2,10)):
            coe = int(c)
        elif c == 'm':
            n += coe * 1000
            coe = 1
        elif c == 'c':
            n += coe * 100
            coe = 1
        elif c == 'x':
            n += coe * 10
            coe = 1
        elif c == 'i':
            n += coe * 1
            coe = 1
    return n

n = int(input())
for i in range(n):
    ns = input().split()
    s = decode(ns[0]) + decode(ns[1])
    print(encode(s))

Submission status: Accepted

Solution code:

def MCXI_integer(mcxi):
    n = 0
    buff = 1
    for c in mcxi:
        if c in 'mcxi':
            buff *= 10**(3-['m', 'c', 'x', 'i'].index(c))
            n += buff
            buff = 1
        else:
            buff = int(c)
    return n

def integer_MCXI(n):
    mcxi = ''
    buff = 0
    for i in range(4):
        buff = n%(10**(4-i))//(10**(3-i))
        if buff == 0:
            pass
        elif buff == 1:
            mcxi += 'mcxi'[i]
        else:
            mcxi += str(buff) + 'mcxi'[i]
    return mcxi



def main():
    n = int(input())
    for _ in range(n):
        s = [x for x in input().split()]
        print(integer_MCXI(MCXI_integer(s[0]) + MCXI_integer(s[1])))

if __name__ == '__main__':
    main()

Submission status: Accepted

Solution code:

def from_mcxi(s):
	n = 0
	t = 1
	for c in s:
		if c == 'm':
			n += t*1000
		elif c == 'c':
			n += t*100
		elif c == 'x':
			n += t*10
		elif c == 'i':
			n += t*1
		else:
			t = int(c)
		if c in 'mcxi':
			t = 1
	return n

def to_mcxi(n):
	s = ''
	if (n // 1000) > 0:
		if (n // 1000) > 1:
			s += str(n // 1000)
		s += 'm'
	if (n % 1000 // 100) > 0:
		if (n % 1000 // 100) > 1:
			s += str(n % 1000 // 100)
		s += 'c'
	if (n % 100 // 10) > 0:
		if (n % 100 // 10) > 1:
			s += str(n % 100 // 10)
		s += 'x'
	if (n % 10) > 0:
		if (n % 10) > 1:
			s += str(n % 10)
		s += 'i'
	return s

n = int(input())
for i in range(n):
	s = input().split()
	print(to_mcxi(from_mcxi(s[0]) + from_mcxi(s[1])))

Submission status: Accepted

Solution code:
#num-> MCXI str
#num <- int
def encode(num):
    M=num/1000
    num-=1000*M
    C=num/100
    num-=100*C
    X=num/10
    num-=X*10
    I = num
    res=""
    l=[M,C,X,I]
    char=['m','c','x','i']
    for i in range(4):
        if (l[i]==0):
            pass
        elif (l[i]==1):
            res=res+char[i]
        else:
            res=res+str(l[i])+char[i]
    return res

# MCXI str -> int
# char<- MCXI str
def decode(char):
    M=C=X=I=0
    if ('m' in char):
        char=char.split("m")
        if (not char[0]):M=1
        else:M=int(char[0])
        char=char[1]        
    if ('c' in char):
        char=char.split('c')
        if (not char[0]):C=1
        else:C=int(char[0])
        char=char[1]
    if ('x' in char):
        char=char.split('x')
        if(not char[0]):X=1
        else: X=int(char[0])
        char=char[1]
    if ('i' in char):
        char=char.split('i')
        if(not char[0]): I=1
        else: I=int(char[0])
        char=char[1]
    res=M*1000+C*100+X*10+I*1
    return res

n = int(raw_input())
for i in range(n):
    l = raw_input()
    
    l = l.split(" ")
    x=l[0]
    y=l[1]
    X=decode(x)
    Y=decode(y)
    
    res=encode(X+Y)
    print res

Submission status: Accepted

Solution code:
import math

n = int(input())

def mcxi2int(s):
    m = {'m': 1000, 'c': 100, 'x': 10, 'i': 1}

    ret = 0
    i = 0
    while i < (len(s)):
        num = 1
        maci = s[i]
        if maci.isdigit():
            num = int(maci)
            maci = s[i + 1]
            i += 1
        ret += num * m[maci]
        i += 1
    return ret


def int2mcxi(n):
    keys = ['m', 'c', 'x', 'i']
    values = [1000, 100, 10, 1]

    ret = ""
    for k, v in zip(keys, values):
        i = n / v
        n = n % v
        if i == 0:
            continue
        elif i == 1:
            ret = ret + k
        else:
            ret = ret + str(i) + k
    return ret

for _ in range(n):
    m1, m2 = raw_input().split()
    print int2mcxi(mcxi2int(m1) + mcxi2int(m2))

Submission status: Accepted

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

import re

PATTERN = re.compile(r"[2-9]*[mcxi]")
NUMBERS = "23456789"
TABLE = {"m": 1000, "c": 100, "x": 10, "i": 1}


def mcxi2int(mcxi_str):
    answer = 0
    for segment in re.findall(PATTERN, mcxi_str):
        answer += TABLE[segment[-1]] * \
            (int(segment[0]) if segment[0] in NUMBERS else 1)
    return answer


def int2mcxi(number):
    mcxi_prefixes = dict()
    mcxi_prefixes["m"], cxi = divmod(number, 1000)
    mcxi_prefixes["c"], xi = divmod(cxi, 100)
    mcxi_prefixes["x"], mcxi_prefixes["i"] = divmod(xi, 10)
    result = ""
    for char in "mcxi":
        if mcxi_prefixes[char] == 1:
            result += char
        elif mcxi_prefixes[char] > 1:
            result += str(mcxi_prefixes[char]) + char
    return result


if __name__ == "__main__":
    n = int(input())
    for i in range(n):
        mcxi1, mcxi2 = input().split()
        print(int2mcxi(mcxi2int(mcxi1) + mcxi2int(mcxi2)))

Submission status: Accepted

Solution code:
trial = int(input())
numlist = [str(n) for n in range(2,10)]

cases = []
for t in range(trial):
    cases.append(input().split(" "))
for case in range(len(cases)):
    num = 0
    for ba in range(2):
        #print(num)
        for n in range(len(cases[case][ba])):
                if cases[case][ba][n] == "m":
                    if n - 1 == 0:
                        num += int(cases[case][ba][n-1]) * 1000
                    else:
                        num += 1000
                elif cases[case][ba][n] == "c":
                    if (n - 1 == 0 and cases[case][ba][n-1] != "m") or cases[case][ba][n-1] in numlist:
                        num += int(cases[case][ba][n-1]) * 100
                    else:
                        num += 100
                elif cases[case][ba][n] == "x":
                    if (n - 1 == 0 and cases[case][ba][n-1] not in ["m","c"]) or cases[case][ba][n-1] in numlist:
                        num += int(cases[case][ba][n-1]) * 10
                    else:
                        num += 10
                elif cases[case][ba][n] == "i":
                    if (n - 1 == 0 and cases[case][ba][n-1] not in ["m","c","x"]) or cases[case][ba][n-1] in numlist:
                        num += int(cases[case][ba][n-1]) * 1
                    else:
                        num += 1
    else:
        num = str(num)
        answer = ""
        for n in range(len(num)):
            if len(num) - 1 - n == 3:
                if num[n] == "1":
                    answer += "m"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "m"
            if len(num) - 1 - n == 2:
                if num[n] == "1":
                    answer += "c"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "c"
            if len(num) - 1 - n == 1:
                if num[n] == "1":
                    answer += "x"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "x"
            if len(num) - 1 - n == 0:
                if num[n] == "1":
                    answer += "i"
                elif num[n] == "0":
                    pass
                else:
                    answer += str(num[n]) + "i"
        else:
            print(answer)

Submission status: Accepted

Solution code:
#coding: utf-8

n = int(raw_input())

def conv1(s):
    a = 0
    st = ['i', 'x' , 'c', 'm']
    for i in range(4):
        if s.find(st[i]) != -1:
            index = s.find(st[i])
            try:
                a = a + 10 ** i * int(s[index - 1])
            except:
                a = a + 10 ** i
    return a

def conv2(num):
    re = ''
    st = ['i', 'x' , 'c', 'm']
    for i in range(4):
        a = num % 10
        num = num / 10
        if a == 0:
            continue
        elif a == 1:
            re = st[i] + re
        else:
            re = str(a) + st[i] + re
    return re

for i in range(n):
    l = raw_input().split()
    print conv2(conv1(l[0]) + conv1(l[1]))

Submission status: Accepted

Solution code:
w={"m":1000, "c":100, "x":10, "i":1}
def mcxiToNum(s):
    res=0
    while len(s)>0:
        if s[0] in w:
            res+=w[s[0]]
            s=s[1:]
        else:
            res+=w[s[1]]*int(s[0])
            s=s[2:]
    return res

def numToMcxi(n):
    s="ixcm"
    res=""
    for i in xrange(4):
        if n%10==0:
            res=res
        elif n%10==1:
            res=s[i]+res
        else:
            res=str(n%10)+s[i]+res
        n/=10
    return res

n=int(raw_input())
for _ in xrange(n):
    x,y=raw_input().split()
    print numToMcxi(mcxiToNum(x)+mcxiToNum(y))

Submission status: Accepted

Solution code:
d = {'m':1000,'c':100,'x':10,'i':1}
k = ['i','x','c','m']
def digit(s):
    r,p = 0,1
    for x in s:
        if x.isdigit(): p = int(x)
        else:
            r += p*d[x]
            p = 1
    return r

for _ in range(int(input())):
    a,b = input().split()
    s = digit(a)+digit(b)
    r = []
    for i,x in enumerate(reversed(str(s))):
        if x!='0': r += [x+k[i]] if x!='1' else [k[i]]
    print(*reversed(r),sep='')

Submission status: Accepted

Solution code:
a={'m':1000,'c':100,'x':10,'i':1}
for _ in range(int(input())):
    b,s,t=input(),0,1
    for x in b:
        if x==' ':continue
        if x in a:s+=a[x]*t;t=1
        else:t=int(x)
    ans=''
    for k in ['m','c','x','i']:
        c,s=divmod(s,a[k])
        if c:ans+=['',str(c)][c!=1]+k
    print(ans)

Submission status: Accepted

Solution code:
a={'m':1000,'c':100,'x':10,'i':1}
for _ in range(int(input())):
    b,s,t=input().replace(' ',''),0,1
    for x in b:
        if x in a:s+=a[x]*t;t=1
        else:t=int(x)
    d=''
    for k in ['m','c','x','i']:
        c,s=divmod(s,a[k])
        if c:d+=['',str(c)][c!=1]+k
    print(d)

Submission status: Accepted

Solution code:
di = {"m":1000,"c":100,"x":10,"i":1}
num = input()

def decod(st):
    buf = 1
    tot = 0
    for i in st:
        if ((i == 'm') or (i == 'c') or (i == 'x') or (i == 'i')):
            tot += buf * di[i]
            buf = 1
        else:
            buf = int(i)
    return tot


def encod(num):
    l = []
    st2 = ""
    st = str(num)
    st = "0"*(4-len(st)) + st
    for i in range(len(st)):
        l.append(st[len(st) - (i + 1):len(st) - i])
    for i in range(len(l)):
        st2 += l[3-i] + di.keys()[3-i]
    st2 = st2.replace("0m", "").replace("1m", "m").replace("0c", "")\
        .replace("1c", "c").replace("0x", "").replace("1x", "x")\
        .replace("0i", "").replace("1i", "i")
    return st2

for j in range(num):
    op1,op2 = raw_input().split()
    print encod(decod(op1)+decod(op2))