USACO Preface Numbering

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
/*
ID: wcr19961
PROG: preface
LANG: C++11
*/
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <string>
#include <vector>
using namespace std;

typedef long long LL;
const char s[] = "IVXLCDM";
const string base[4][10] = {
{"", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"},
{"", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"},
{"", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"},
{"", "M", "MM", "MMM"}
};
int cnt[4][10][7], ans[7];

int main() {
freopen("preface.in", "r", stdin);
freopen("preface.out", "w", stdout);
for (int i = 0; i < 4; ++i) {
for (int j = 1; j <= 9; ++j) {
for (int k = 0; k < base[i][j].length(); ++k) {
char c = base[i][j][k];
if (c == 'I') {
++cnt[i][j][0];
} else if (c == 'V') {
++cnt[i][j][1];
} else if (c == 'X') {
++cnt[i][j][2];
} else if (c == 'L') {
++cnt[i][j][3];
} else if (c == 'C') {
++cnt[i][j][4];
} else if (c == 'D') {
++cnt[i][j][5];
} else if (c == 'M') {
++cnt[i][j][6];
}
}
}
}
int n;
scanf("%d", &n);
for (int i = 1; i <= n; ++i) {
int k = 0, x = i;
while (x) {
int tmp = x % 10;
for (int j = 0; j < 7; ++j) {
ans[j] += cnt[k][tmp][j];
}
x /= 10;
++k;
}
}
for (int i = 0; i < 7; ++i) {
if (ans[i] > 0) {
printf("%c %d\n", s[i], ans[i]);
}
}
return 0;
}