import java.util.*; public class Roman_bob { public static Scanner in; public static int n; public static int[] val; public static String[] lookup1, lookup2, lookup3,sorted,v; public static int vx, cdilm; public static String ms; public static void main(String[] args) { // Set up: lookup1 = new String[]{"","I","II","III","IV","V","VI","VII","VIII","IX"}; lookup2 = new String[]{"","X","XX","XXX","XL","L","LX","LXX","LXXX","XC"}; lookup3 = new String[]{"","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"}; ms = "M"; // Rather than counting out leading "M"s in a loop, just // take a substring of appropriate length from this. while (ms.length() < 10e6) // there will be at most 10^6 "M"s ms = ms+ms; // generate all strings for 1..999: v = new String[1000]; v[0] = ""; for (int i = 1; i < 1000; i++) { v[i] = convert(i); } Arrays.sort(v); // find where the "V"s start: vx = 999; while (! v[vx].equals("V")) vx--; cdilm = vx; vx = 1000-vx; // Start reading in: in = new Scanner(System.in); n = in.nextInt(); val = new int[n]; for (int i = 0; i < n; i++) { val[i] = in.nextInt(); } for (int i = 0; i < n; i++) { process(val[i]); } } public static void process(int i) { int ans = 0; // first, convert: String c = convert(i); // Look at everything after the (possibly empty) leading // string of "M"s. If this "tail" begins with V or X, count from end, // else count from beginning. // There might be lots of Ms, so count back from end of c: int j = c.length()-1; while (j >= 0 && c.charAt(j) != 'M') j--; // Special case: ...MMCM... if (j >= 1 && c.charAt(j-1)=='C') j-=2; j++; String tail = c.substring(j); // The "tail" (possibly empty) extends from position j onward. // See if it begins with 'X' or 'V' if (j < c.length() && (c.charAt(j) == 'X' || c.charAt(j) == 'V')) { // locate tail value (must be <= 999): int k = 999; while (! v[k].equals(tail)) k--; ans = k-1000; // negative since we count from the end // Now, for each leading M, subtract // vx (= 54) (the number of strings between (M^x)tail and (M^(x+1))tail // for any integer x)) ans -= j*vx; System.out.println(ans); } else { // tail begins with 'C', 'D', 'I', or 'L' // For each leading M, add on cdilm, the number of strings between // M^x and M^(x+1): ans += cdilm*j; // locate tail value (must be <= 999) and add it on: int k = 999; k = 0; while (k < 1000 && ! v[k].equals(tail)) k++; ans += k; System.out.println(ans); } } public static String convert(int i) { String ans = lookup1[i%10]; i = i/10; ans = lookup2[i%10]+ans; i = i/10; ans = lookup3[i%10]+ans; i = i/10; // Could be lots of Ms, so look it up rather than count: ans = ms.substring(0,i)+ans; return ans; } }