top of page

CCC 1996 S4:When in Rome...


The problem can be solved in two parts:

  1. Rome to digits

  2. Digits to Rome

1. Rome to digits:

if one Rome number, return its digit directly.

if more Rome number, count each same char blocks to same char number,

its value is the number* value of the Rome char, if the Rome char of the next block Rome is bigger than current, the result subtracts the block value, otherwise add the value.

Handle the final block


2. Digits to Rome:

Handle the thousand-digit.

Handle the hundred-digit

Handle the ten-digit

Handle the digit.



N = int(input())
rtable = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
hundreds = {9:"CM", 8:"DCCC", 7:"DCC", 6:"DC", 5:"D", 4:"CD", 3:"CCC", 2:"CC", 1:"C", 0:""}
tens = {9:"XC", 8:"LXXX", 7:"LXX", 6:"LX", 5:"L", 4:"XL", 3:"XXX", 2:"XX", 1:"X", 0:""}
ones = {9:"IX", 8:"VIII", 7:"VII", 6:"VI", 5:"V", 4:"IV", 3:"III", 2:"II", 1:"I",0:""}

def romantodigit(ss, last):
    i = 1
    c = ss[0]
    cn = 1
    m = len(ss)
    if last == 1:
        m -= 1
    if m == 1:
        return rtable[c]
    result = 0
    while i < m:
        while i < m and ss[i] == c:
           cn += 1
           i += 1
        if i < m:
            if rtable[ss[i]] > rtable[c]:
                result -= cn*rtable[c]
            else:
                result += cn * rtable[c]
            cn = 1
            c = ss[i]
            i += 1
        if i == m:
            result += cn * rtable[c]
    return result


def digittoroman(n):
    if n == 1000:
        return "D"
    s = ""
    m = n // 100
    n %= 100
    s1 = s+hundreds[m]
    m = n // 10
    n %= 10
    s2 = s1+tens[m]
    s3 = s2+ones[n]
    return s3


for i in range(N):
    ss = input()
    s = ss.split("+")
    n1 = romantodigit(s[0], 0)
    n2 = romantodigit(s[1], 1)
    if n1 + n2 > 1000:
        print(ss+"CONCORDIA CUM VERITATE")
    else:
        print(ss+digittoroman(n1+n2))



Recent Posts

See All

CCC '24 J5 - Harvest Waterloo

#include<iostream> #include <vector> #include <algorithm> #include <cmath> #include <stack> using namespace std; int main() { int r, c, sr, sc; cin >> r; cin >> c; int p[r][c]; bool v

CCC '24 J4 - Troublesome Keys

#include <iostream> #include <string> #include <map> #include <vector> #include <algorithm> #include <cmath> using namespace std; int main() { string ps; string ds; cin >> ps; cin >> ds;

CCC '22 J5 - Square Pool

#include<iostream> #include <vector> #include <algorithm> #include <cmath> using namespace std; bool rowcom(pair<int, int> a, pair<int, int> b){ return a.first < b.first; } bool colcom(pair<int,

Comentários


bottom of page