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: Accepted

Solution code:
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", ""))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
# coding: utf-8
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')))

Submission status: Accepted

Solution code:
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')))

Submission status: Accepted

Solution code:
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','')))

Submission status: Accepted

Solution code:
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','')))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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:
		# print(j,end="")
		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()

Submission status: Accepted

Solution code:
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))))

Submission status: Accepted

Solution code:
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

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

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])
    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:
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","")

Submission status: Accepted

Solution code:
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

Submission status: Accepted

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

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

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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))

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
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)

Submission status: Accepted

Solution code:
#2005_c

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

Submission status: Accepted

Solution code:
ans_list = []
# m:1000, c:100. x:10, i:1
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)

Submission status: Accepted

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

Submission status: Accepted

Solution code:
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)))

Submission status: Accepted

Solution code:
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')