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 (<= 500) that 
indicates the number of the following lines.  
The k +1 th line is the specification of 
the k th computation ( k =1, ..., n ).  n   specification 1   specification 2  ...  specification n   Each specification is described in a line:  MCXI-string 1  MCXI-string 2   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

Solution (Python):
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))

Solution (Python):
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))
    
    
    ans = digit2mcxl(ans)
    ans_list.append(ans)
for i in ans_list:
    print("".join(i))

Solution (Python):
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)

Solution (Python):
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())))

Solution (Python):
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)

Solution (Python):



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)

Solution (Python):
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))

Solution (Python):
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))

Solution (Python):

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()

Solution (Python):

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])))

Solution (Python):


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



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

Solution (Python):
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))

Solution (Python):



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)))

Solution (Python):
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):
        
        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)

Solution (Python):


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]))

Solution (Python):
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))

Solution (Python):
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='')

Solution (Python):
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)

Solution (Python):
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)

Solution (Python):
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))

Solution (Python):
mcxi = {"m": 1000, "c": 100, "x": 10, "i": 1}
nums = [str(i) for i in range(2, 10)]

def calc(s):
    tmp = 0
    while s:
        c = s.pop()
        if c in nums:
            a = int(c)
            if len(s) == 0:
                tmp += a
                break
            c = s.pop()
            tmp += a * mcxi[c]
        else:
            tmp += mcxi[c]
    return tmp

n = int(input())
for _ in range(n):
    mcxis = input().split()
    a = ' '.join(mcxis[0]).split()[::-1]
    b = ' '.join(mcxis[1]).split()[::-1]
    tmp = calc(a) + calc(b)
    m, tmp = divmod(tmp, 1000)
    c, tmp = divmod(tmp, 100)
    x, i = divmod(tmp, 10)
    ans = ""
    if m > 0:
        ans += str(m)+"m"
    if c > 0:
        ans += str(c)+"c"
    if x > 0:
        ans += str(x)+"x"
    if i > 0:
        ans += str(i)+"i"
    print(ans.replace("1", ""))

Solution (Python):
import sys

inf = 1<<30

def solve():
    n = int(sys.stdin.readline().rstrip())

    for i in range(n):
        x, y = sys.stdin.readline().split()

        x = mcxi_to_digit(x)
        y = mcxi_to_digit(y)

        ans = digit_to_mcxi(x + y)

        print(ans)

def mcxi_to_digit(x):
    res = 0
    ps = -1

    for i, num in enumerate(x):
        if ps == i:
            continue
        if num.isdigit():
            if x[i + 1] == 'm':
                res += 1000 * int(num)
            elif x[i + 1] == 'c':
                res += 100 * int(num)
            elif x[i + 1] == 'x':
                res += 10 * int(num)
            else:
                res += int(num)

            ps = i + 1
        else:
            if num == 'm':
                res += 1000
            elif num == 'c':
                res += 100
            elif num == 'x':
                res += 10
            else:
                res += 1

    return res

def digit_to_mcxi(x):
    res = []

    if x % 10 == 1:
        res.append('i')
    elif x % 10 > 1:
        res.append('i')
        res.append(str(x % 10))

    x //= 10

    if x % 10 == 1:
        res.append('x')
    elif x % 10 > 1:
        res.append('x')
        res.append(str(x % 10))

    x //= 10

    if x % 10 == 1:
        res.append('c')
    elif x % 10 > 1:
        res.append('c')
        res.append(str(x % 10))

    x //= 10

    if x % 10 == 1:
        res.append('m')
    elif x % 10 > 1:
        res.append('m')
        res.append(str(x % 10))

    res.reverse()

    return ''.join(res)

if __name__ == '__main__':
    solve()

Solution (Python):
import sys

inf = 1<<30

def solve():
    n = int(sys.stdin.readline().rstrip())

    for i in range(n):
        x, y = sys.stdin.readline().split()

        x = mcxi_to_digit(x)
        y = mcxi_to_digit(y)

        ans = digit_to_mcxi(x + y)

        print(ans)

def mcxi_to_digit(x):
    res = 0
    ps = -1

    mcxi = {'m':1000, 'c':100, 'x':10, 'i':1}

    for i, num in enumerate(x):
        if ps == i:
            continue
        if num.isdigit():
            res += mcxi[x[i + 1]] * int(num)
            ps = i + 1
        else:
            res += mcxi[num]

    return res

def digit_to_mcxi(x):
    res = []
    mcxi = ['i', 'x', 'c', 'm']

    for k in range(len(mcxi)):
        if x % 10 >= 1:
            res.append(mcxi[k])

            if x % 10 > 1:
                res.append(str(x % 10))

        x //= 10
        
    res.reverse()

    return ''.join(res)

if __name__ == '__main__':
    solve()

Solution (Python):
def decode(s):
    ret = 0
    u = 1
    for c in 'ixcm':
        i = s.find(c)
        if i < 0:
            pass
        elif i == 0 or not s[i-1].isdigit():
            ret += u
        else:
            ret += u * int(s[i-1])
        u *= 10
    return ret

def encode(n):
    ret = ''
    for c in 'ixcm':
        d = n % 10
        if d == 1:
            ret = c + ret
        elif d > 1:
            ret = str(d) + c + ret
        n //= 10
    return ret

N = int(input())
for i in range(N):
    a,b = input().split()
    print(encode(decode(a) + decode(b)))

Solution (Python):

import re
for i in range(int(input())):
    s=input().replace(" ","")
    print(''.join(re.sub(r'0\w','',''.join([i+j for (i,j) in zip(str(10000+eval('+'.join([i[0]+{'m':'*1000','c':'*100','x':'*10','i':''}[i[1]] for i in ['1'+i for i in ''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)])))[1:],list('mcxi'))])).split('1')))

Solution (Python):
import re
for i in range(int(input())):
 s=input().replace(" ","")
 print(''.join(re.sub(r'0\w','',''.join([i+j for(i,j)in zip(str(10000+eval('+'.join([i[0]+{'m':'*1000','c':'*100','x':'*10','i':''}[i[1]]for i in ['1'+i for i in''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)])))[1:],list('mcxi'))])).split('1')))

Solution (Python):
import re
for i in range(int(input())):
 s=input().replace(" ","")
 print(re.sub(r'0.','',''.join([i+j for(i,j)in zip(str(10000+eval('+'.join([i[0]+{'m':'*1000','c':'*100','x':'*10','i':''}[i[1]]for i in ['1'+i for i in''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)])))[1:],list('mcxi'))]).replace('1','')))

Solution (Python):
import re
for i in range(int(input())):
 s=input().replace(" ","")
 print(re.sub(r'0.','',''.join([i+j for(i,j)in zip(str(10000+sum([eval(i[0]+'0'*'ixcm'.find(i[1]))for i in['1'+i for i in''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)])),list('1mcxi'))]).replace('1','')))

Solution (Python):
import re
[print(re.sub(r'0.','',''.join([str(10000+sum([eval(i[0]+'0'*'ixcm'.find(i[1]))for i in['1'+i for i in''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)]))[i]+'1mcxi'[i]for i in range(5)]).replace('1','')))for s in[input().replace(" ","")for i in range(int(input()))]]

Solution (Python):
import re
[print(re.sub(r'0.','',''.join([str(10000+sum([eval(i[0]+'0'*'ixcm'.find(i[1]))for i in['1'+i for i in''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)]))[i]+'1mcxi'[i]for i in range(5)]).replace('1','')))for s in[input().replace(" ","")for i in range(int(input()))]]

Solution (Python):
import re;[print(re.sub(r'0.','',''.join([str(10000+sum([eval(i[0]+'0'*'ixcm'.find(i[1]))for i in['1'+i for i in''.join(re.split(r'\d\w',s))]+re.findall(r'\d\w',s)]))[i]+'1mcxi'[i]for i in range(5)]).replace('1','')))for s in[input().replace(" ","")for i in range(int(input()))]]

Solution (Python):
mcxi = "mcxi"
mcxinum = [1000, 100, 10, 1]

n = int(input())
for z in range(n):
    nums = list(input().split())

    ans = 0
    for num in nums:
        for ind, c in enumerate(mcxi):
            if c in num:
                prestr, num = num.split(c)
                pre = 1
                if prestr:
                    pre = int(prestr)
                ans += pre * mcxinum[ind]

    ansstr = ""
    for j in range(4):
        dig = mcxinum[j]
        if ans >= dig:
            dign = ans // dig
            if dign > 1:
                ansstr += str(dign)
            ansstr += mcxi[j]
            ans %= dig

    print(ansstr)

Solution (Python):
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools

sys.setrecursionlimit(10**7)
inf = 10**20
eps = 1.0 / 10**10
mod = 10**9+7

def LI(): return [int(x) for x in sys.stdin.readline().split()]
def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()]
def LF(): return [float(x) for x in sys.stdin.readline().split()]
def LS(): return sys.stdin.readline().split()
def I(): return int(sys.stdin.readline())
def F(): return float(sys.stdin.readline())
def S(): return input()
def pf(s): return print(s, flush=True)

def main():
    rr = []
    n = I()
    a = [LS() for _ in range(n)]

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

    def g(i):
        r = ''
        if i >= 1000:
            k = i // 1000
            if k > 1:
                r += str(k)
            r += 'm'
            i %= 1000
        if i >= 100:
            k = i // 100
            if k > 1:
                r += str(k)
            r += 'c'
            i %= 100
        if i >= 10:
            k = i // 10
            if k > 1:
                r += str(k)
            r += 'x'
            i %= 10
        if i >= 1:
            k = i
            if k > 1:
                r += str(k)
            r += 'i'
        return r

    for s,t in a:
        rr.append(g(f(s)+f(t)))

    return '\n'.join(map(str, rr))


print(main())

Solution (Python):
import sys
sys.setrecursionlimit(10**6)

def toord(st):
	ans = ""
	if st//1000 != 0:
		if st // 1000 != 1:
			ans += str(st//1000)
		ans+="m"
		st = st % 1000
	if st // 100 != 0:
		if st // 100 != 1:
			ans += str(st//100)
		ans += "c"
		st = st % 100
	if st // 10 != 0:
		if st // 10 != 1:
			ans += str(st//10)
		ans += "x"
		st = st % 10
	if st != 0:
		if st!=1:
			ans += str(st)
		ans += "i"
	return ans
			

def main():
	a,b = input().split()
	a, b = "+" + a, "+"+b
	a, b = a.replace("m","*m+"), b.replace("m", "*m+")
	a, b = a.replace("c","*c+"), b.replace("c", "*c+")
	a, b = a.replace("x","*x+"), b.replace("x", "*x+")
	a, b = a.replace("i","*i+"), b.replace("i", "*i")
	ans, tans = 0, 0
	for j in a+b:
		
		if j == "+":
			tans = 1
		elif j == "*":
			ans = ans
		elif j == "m":
			tans *= 1000
			ans += tans
		elif j == "c":
			tans *= 100
			ans += tans
		elif j == "x":
			tans *= 10
			ans += tans
		elif j == "i":
			ans += tans			
		else:
			tans = int(j)
	print(toord(ans))
	return

n = int(input())
for i in range(n):
	main()

Solution (Python):
def mtoi(l):
    r=0
    c=1
    for i in l:
        if i=="m":
            r+=c*1000
            c=1
        elif i=="c":
            r+=c*100
            c=1
        elif i=="x":
            r+=c*10
            c=1
        elif i=="i":
            r+=c
            c=1
        else:
            c=int(i)
    return r


def itom(r):
    m=r//1000
    c=r//100-m*10
    x=r//10-m*100-c*10
    i=r-1000*m-100*c-10*x
    t=""
    if m:
        if m==1:t+="m"
        else:t+=str(m)+"m"
    if c:
        if c==1:t+="c"
        else:t+=str(c)+"c"
    if x:
        if x==1:t+="x"
        else:t+=str(x)+"x"
    if i:
        if i==1:t+="i"
        else:t+=str(i)+"i"
    return t

for _ in range(int(input())):
    l=input().split()
    print(itom(sum(map(mtoi,l))))