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):
n = int(raw_input())
num = [1000, 100, 10, 1]
cha = ['m', 'c', 'x', 'i']
for i in xrange(n):
    po = raw_input().split()
    poyo = [0, 0]
    for j in xrange(2):
        c = 1
        for k in xrange(len(po[j])):
            if po[j][k] == cha[0]:
                poyo[j] += c*num[0]
                c = 1
            elif po[j][k] == cha[1]:
                poyo[j] += c*num[1]
                c = 1
            elif po[j][k] == cha[2]:
                poyo[j] += c*num[2]
                c = 1
            elif po[j][k] == cha[3]:
                poyo[j] += c
                break
            else:
                c = int(po[j][k])
    sumpoyo = sum(poyo)
    cn = [0,0,0,0]
    ans = ''
    for j in xrange(4):
        while (sumpoyo >= num[j]):
            sumpoyo -= num[j]
            cn[j] += 1
    for j in xrange(4):
        if cn[j] > 0:
            if cn[j] > 1:
                ans += str(cn[j]) + cha[j]
            else:
                ans += cha[j]
    print ans

Solution (Python):
import sys


def parse(n):
    temp = 0
    digit = 1
    for c in n:
        if c == 'm':
            temp += digit * 1000
            digit = 1
        elif c == 'c':
            temp += digit * 100
            digit = 1
        elif c == 'x':
            temp += digit * 10
            digit = 1
        elif c == 'i':
            temp += digit
            digit = 1
        else:
            digit = int(c)
    return temp

def transform(n):
    temp = ''
    key = ['i', 'x', 'c', 'm']
    for i in xrange(3, -1, -1):
        digit = n / (10**i)
        if digit > 0:
            temp += '' if digit == 1 else str(digit)
            temp += key[i]
            n %= 10**i
    return temp


n = int(sys.stdin.readline())
for z in xrange(n):
    a, b = sys.stdin.readline().split()
    print transform(parse(a) + parse(b))

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

Solution (Python):
dic = {"i":1,"x":10,"c":100,"m":1000}
for r in range(input()):
	a,b = raw_input().split()
	s = 0
	for i in range(len(a)-1,-1,-1):
		if a[i] in "ixcm":
			try: s += int(a[i-1])*dic[a[i]]
			except: s += dic[a[i]]
	for i in range(len(b)-1,-1,-1):
		if b[i] in "ixcm":
			try: s += int(b[i-1])*dic[b[i]]
			except: s+= dic[b[i]]
	s = str(s)
	ans = ""
	for i in range(len(s)):
		if int(s[-i-1]) > 0:
			ans += "ixcm"[i] + s[-i-1]
	print ans[::-1].replace("1","")

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

n = int(raw_input())
for i in range(n):
  a, b = raw_input().split()
  sum = mxciToDegit(a) + mxciToDegit(b)

  st = ""
  list =((1000, "m"), (100, "c"), (10, "x"), (1, "i"))
  for d, c in list:
    val = sum/d
    if val >= 2:
      st += str(val) + c
    elif val == 1:
      st += c
    sum = sum%d
  print st

Solution (Python):


import sys

'''

'''

def func():
    '''

    '''
    n = int(raw_input())

    for i in range(n):
        numstr1, numstr2 = raw_input().split()
        
        num1 = 0
        for index, c in enumerate(numstr1):
            if c == 'm':
                if index != 0 and numstr1[index-1].isdigit():
                    num1 += int(numstr1[index-1]) * 1000
                else:
                    num1 += 1000
            if c == 'c':
                if index != 0 and numstr1[index-1].isdigit():
                    num1 += int(numstr1[index-1]) * 100
                else:
                    num1 += 100
            if c == 'x':
                if index != 0 and numstr1[index-1].isdigit():
                    num1 += int(numstr1[index-1]) * 10
                else:
                    num1 += 10

            if c == 'i':
                if index != 0 and numstr1[index-1].isdigit():
                    num1 += int(numstr1[index-1])
                else:
                    num1 += 1

        num2 = 0
        for index, c in enumerate(numstr2):
            if c == 'm':
                if index != 0 and numstr2[index-1].isdigit():
                    num2 += int(numstr2[index-1]) * 1000
                else:
                    num2 += 1000
            if c == 'c':
                if index != 0 and numstr2[index-1].isdigit():
                    num2 += int(numstr2[index-1]) * 100
                else:
                    num2 += 100
            if c == 'x':
                if index != 0 and numstr2[index-1].isdigit():
                    num2 += int(numstr2[index-1]) * 10
                else:
                    num2 += 10

            if c == 'i':
                if index != 0 and numstr2[index-1].isdigit():
                    num2 += int(numstr2[index-1])
                else:
                    num2 += 1

        s = num1 + num2
        sstr = ''

        if s / 1000 == 0:
            pass
        elif s / 1000 == 1:
            sstr += 'm'
        else:
            sstr += str(s / 1000) + 'm'
                    
        if (s / 100) % 10 == 0:
            pass
        elif (s / 100) % 10 == 1:
            sstr += 'c'
        else:
            sstr += str((s / 100) % 10) + 'c'

        if (s / 10) % 10 == 0:
            pass
        elif (s / 10) % 10 == 1:
            sstr += 'x'
        else:
            sstr += str((s / 10) % 10) + 'x'
        
        if s % 10 == 0:
            pass
        elif s % 10 == 1:
            sstr += 'i'
        else:
            sstr += str(s % 10) + 'i'

        print sstr


if __name__ == '__main__':
    func()

Solution (Python):
def m_i(l):
    stack = 1
    ans = 0
    l = list(l)
    for i in l :
        if i == 'm' :
            ans += stack * 1000
            stack = 1
        elif i == 'c' :
            ans += stack * 100
            stack = 1
        elif i == 'x' :
            ans += stack * 10
            stack = 1
        elif i == 'i' :
            ans += stack
            stack = 1
        else :
            stack = int(i)
    return ans
    
def i_m(l):
    ans = []
    a = l // 1000
    if a == 1 :
        ans.append('m')
    elif a != 0 :
        ans.append(str(a))
        ans.append('m')
    l -= a * 1000
    a = l // 100
    if a == 1 :
        ans.append('c')
    elif a != 0 :
        ans.append(str(a))
        ans.append('c')
    l -= a * 100
    a = l // 10
    if a == 1 :
        ans.append('x')
    elif a != 0 :
        ans.append(str(a))
        ans.append('x')
    a = l - a * 10
    if a == 1 :
        ans.append('i')
    elif a != 0 :
        ans.append(str(a))
        ans.append('i')
    ans = ''.join(ans)
    return ans

n = int(input())
for i in range(n) :
    a, b = input().split()
    ans = m_i(a) + m_i(b)
    print(i_m(ans))

Solution (Python):
n = int(input())
S = ["m", "c", "x", "i"]
X = [1000, 100, 10, 1]
N = [str(i) for i in range(2, 10)]


for i in range(n) :
    A, B = map(str, input().split())
    A = list(A)
    B = list(B)
    ans = 0
    
    for j in range(len(A)) :
        if(A[j] in S) :
            if(j != 0 and A[j - 1] in N) :
                ans += int(A[j - 1]) * X[S.index(A[j])]
            else :
                ans += X[S.index(A[j])]
        
        else :
            pass
            
    for j in range(len(B)) :
        if(B[j] in S) :
            if(j != 0 and B[j - 1] in N) :
                ans += int(B[j - 1]) * X[S.index(B[j])]
            else :
                ans += X[S.index(B[j])]
        
        else :
            pass
    
    ANS = list(str(ans))
    l = len(ANS)
    
    for j in range(l) :
        if(ANS[j] == "0") :
            pass
        elif(ANS[j] == "1") :
            print(S[j + (4 - l)], end = "")
        else :
            print(ANS[j], S[j + (4 - l)], sep = "", end = "")
        
    print()

Solution (Python):
import sys
input = sys.stdin.readline

n = int(input())
fs = [input().split() for i in range(n)]
check = "mcxi"

for f2 in fs:
    v = [0, 0, 0, 0]
    for f in f2:
        for i in range(len(f)):
            for c in range(4):
                if check[c] == f[i]:
                    if i==0:
                        tmp = 1
                    else:
                        tmp = 1 if f[i-1] in check else int(f[i-1])
                    v[c] += tmp
                    break
    for i in range(3, 0, -1):
        if v[i] > 9:
            v[i] -= 10
            v[i-1] += 1
    for i in range(4):
        if v[i] > 0:
            print(check[i] if v[i] == 1 else str(v[i])+check[i], end="")
    print()

Solution (Python):
def S(s):
    m = ["i", "x", "c", "m"]
    res = 0
    i = 0
    tmp = 1
    while i < len(s):
        if "2" <= s[i] <= "9":
            tmp = int(s[i])
        else:
            res += tmp * 10 ** m.index(s[i])
            tmp = 1
        i += 1
    return res
def main():
    m1 = ["i", "x", "c", "m"]
    s1, s2 = list(map(str, input().split()))
    ms1 = S(s1)
    ms2 = S(s2)
    ms = ms1 + ms2
    m = str(ms)
    m = m[::-1]
    res = ""
    for i in range(len(m)):
        if m[i] == "0":
            continue
        if m[i] == "1":
            res = m1[i] + res
            continue
        res = m[i] + m1[i] + res
    print(res)


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

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

def L(): return [x for x in input().split()]
def LI(): return [int(x) for x in input().split()]
def LF(): return [float(x) for x in input().split()]
def LI_(): return [-1*int(x) for x in input().split()]
def II(): return int(input())
def IF(): return float(input())
def LM(func,n): return [[func(x) for x in input().split()]for i in range(n)]
mod = 1000000007
inf = float('INF')
dic = {"m":1000,"c":100,"x":10,"i":1}

def MCXI(S):
    ret = 0
    for d in "mcxi":
        i =S.find(d)
        if i >=1 and "2"<=S[i-1]<="9":
            ret  += int(S[i-1])*dic[d]
        elif i>=0:
            ret += dic[d]
    return ret
def mcxi(n):
    S = ""
    for d in "ixcm":
        if n%10 == 1:
            S += d
        elif n%10 > 1:
            S += d
            S += str(n%10)
        n //= 10
    return S[::-1]


n = II()

for i in range(n):
    a,b = L()
    a = MCXI(a)
    b= MCXI(b)
    print(mcxi(a+b))

Solution (Python):
n = int(input())
for i in range(n):
    S,T = input().split()
    ans = [0,0,0,0]
    for s in range(len(S)):
        if S[s] in "mcxi":
            if s!=0 and not(S[s-1] in "mcxi"):
                ans["mcxi".find(S[s])] = int(S[s-1])
            else:
                ans["mcxi".find(S[s])] = 1
    for t in range(len(T)):
        if T[t] in "mcxi":
            if t!=0 and not(T[t-1] in "mcxi"):
                ans["mcxi".find(T[t])] += int(T[t-1])
            else:
                ans["mcxi".find(T[t])] += 1
    ans = ans[::-1]
    anstr = ""
    for i in range(4):
        if i<3 and ans[i]>=10:
            ans[i] = ans[i]%10
            ans[i+1] += 1
        if ans[i] > 0:
            anstr = "ixcm"[i] + anstr
            if ans[i]>1:
                anstr = str(ans[i]) + anstr
    print(anstr)

Solution (Python):
dic = {"m":1000, "c":100, "x":10, "i":1}
dic_rev = {1000:"m", 100:"c", 10:"x", 1:"i"}
N = int(input())

for i in range(N):
    slist = list(map(str, input().split()))
    numlist = []
    for word in slist:
        before = 1
        word_sum = 0
        for c in word:
            if c in dic:
                word_sum += (int(before) * dic[c])
                before = 1
            else:
                before = c
        numlist.append(word_sum)

    wordsum = sum(numlist)

    ans = ""
    cnt = 1
    for w in reversed(str(wordsum)):
        if w == "0":
            tmp = ""
        elif w == "1":
            tmp = dic_rev[cnt]
        else:
            tmp = w + dic_rev[cnt]
        ans = tmp + ans
        cnt = cnt * 10

    print(ans)

Solution (Python):


n = int(input())
k = list("mcxi")
for i in range(n):
    d = {"m":0,"c":0,"x":0,"i":0}
    a,b  = input().split()
    a = list(a)
    b = list(b)
    a.insert(0,1)
    b.insert(0,1)
    for j in range(1,len(a)):
        if a[j] in k:
            if a[j-1] in k:
                d[a[j]] += 1
            else:
                d[a[j]] += int(a[j-1])
    for j in range(1,len(b))[::-1]:
        if b[j] in k:
            if b[j-1] in k:
                d[b[j]] += 1
            else:
                d[b[j]] += int(b[j-1])
            if d[b[j]] >= 10:
                l = b[j]
                while d[l] >= 10:
                    d[l] -= 10
                    l = k[k.index(l)-1]
                    d[l] += 1
    for j in k:
        if d[j]:
            if d[j] == 1:
                print(j,end = "")
            else:
                print(str(d[j])+j,end = "")
    print()

Solution (Python):
ans_list = []

n = int(input())

mcxi = list("mcxi")[::-1]

def value(string):
    res = 0
    for i in range(4):
        index = string.find(mcxi[i])
        if index != -1:
            if string[index-1] in mcxi:
                res += pow(10,i)
            else:
                res += int(string[index-1]) * pow(10,i)
    return res

def MCXI(integer):
    res = ""
    for i in range(4):
        remain = integer % 10
        integer //= 10
        if remain == 1:
            res = mcxi[i] + res
        elif remain == 0:
            pass
        else:
            res = str(remain) + mcxi[i] + res
    return res

for _ in range(n):
    s,t = input().split()
    ans = MCXI(value(s) + value(t))
    ans_list.append(ans)

for ans in ans_list:
    print(ans)

Solution (Python):
def main():
    d_num = int(input())
    for i in range(d_num):
        a, b = map(str, input().split(" "))
        print(NtoS(StoN(a) + StoN(b)))

def StoN(mcxi):
    slist = list(mcxi)
    for i in range(len(slist)):
        if slist[i] == 'm': slist[i] = 1000
        elif slist[i] == 'c': slist[i] = 100
        elif slist[i] == 'x': slist[i] = 10
        elif slist[i] == 'i': slist[i] = 1
        else: slist[i] = int(slist[i])
        
    num = 1
    summ = 0
    for item in slist:
        if item == 1000 or item == 100 or item == 10 or item == 1:
            summ += num * item
        else:
            num = item
            continue
        num = 1

    return summ

def NtoS(num):
    mcxi = ""
    n1000 = num // 1000
    n100 = (num - n1000 * 1000) // 100
    n10 = (num - n1000 * 1000 - n100 * 100) // 10
    n1 = (num - n1000 * 1000 - n100 * 100 - n10 * 10)
    
    if n1000 != 0:
        if n1000 == 1: mcxi = mcxi + "m"
        else: mcxi = mcxi + str(n1000) + "m"
    if n100 != 0:
        if n100 == 1: mcxi = mcxi + "c"
        else: mcxi = mcxi + str(n100) + "c"
    if n10 != 0:
        if n10 == 1: mcxi = mcxi + "x"
        else: mcxi = mcxi + str(n10) + "x"
    if n1 != 0:
        if n1 == 1: mcxi = mcxi + "i"
        else: mcxi = mcxi + str(n1) + "i"
    return mcxi
main()

Solution (Python):
def parse(s):
  ret = 0
  dic = {"m":1000, "c":100, "x":10, "i":1}
  while s:
    if s[0] in dic:
      ret += dic[s[0]]
      s = s[1:]
    else:
      ret += int(s[0]) * dic[s[1]]
      s = s[2:]
  return ret

def conv(n):
  ret = ""
  def func(ret, c, i):
    if i == 0:
      pass
    elif i == 1:
      ret += c
    else:
      ret += str(i) + c
    return ret
  a = n // 1000
  ret = func(ret, "m", a)
  n %= 1000
  b = n // 100
  ret = func(ret, "c", b)
  n %= 100
  c = n // 10
  ret = func(ret, "x", c)
  n %= 10
  ret = func(ret, "i", n)
  return ret

n = int(input())
for _ in range(n):
  s1, s2 = input().split()
  print(conv(parse(s1) + parse(s2)))

Solution (Python):
D = "mcxi"
V = [1000, 100, 10, 1]
def conv1(s):
    v = 0; t = 1
    for c in s:
        idx = D.find(c)
        if idx > -1:
            v += t * V[idx]
            t = 1
        else:
            t = int(c)
    return v
def conv2(v):
    s = []
    for i in range(4):
        if v >= V[i]:
            k = v // V[i]
            if k > 1:
                s.append(str(k))
            s.append(D[i])
            v -= k * V[i]
    return "".join(s)

N = int(input())
ans = []
for i in range(N):
    p, q = input().split()
    ans.append(conv2(conv1(p) + conv1(q)))
print(*ans, sep='\n')

Solution (Python):

r=list('mcxi')
m=r[::-1]
n=int(input())
for i in range(n):
    a,b=input().split()
    x=int(''.join(['0' if len(a.split(c))==1 else '1' if a.split(c)[0]=='' or a.split(c)[0][-1] in 'mcxi' else a.split(c)[0][-1] for c in r]))
    y=int(''.join(['0' if len(b.split(c))==1 else '1' if b.split(c)[0]=='' or b.split(c)[0][-1] in 'mcxi' else b.split(c)[0][-1] for c in r]))
    ans=str(x+y)[::-1]
    s=''
    for j in range(len(ans)):
        if(ans[j]!='0'):
            s+=m[j]+(ans[j] if ans[j]!='1' else '')
    print(s[::-1])