USACO 2.2 Preface Numbering

Simple brutal force approach can pass the tests. We iterate through the numbers, for each number converting the numerical value of the number to Roman number representation and then counting.

#include <algorithm>
#include <vector>
#include <iostream>
#include <fstream>
#include <string>
#include <map>
#include <unordered_map>

using namespace std;

int N;

string intToRoman(int num) {
int numbers[13] = {1000, 900, 500, 400, 100, 90, 50, 40,
10, 9, 5, 4, 1};
const char *roman[13] = {"M", "CM", "D", "CD", "C", "XC",
"L", "XL", "X", "IX", "V", "IV", "I"};
string result = "";
for (int i = 0; i < 13; ++i) {
while (num >= numbers[i]) {
num -= numbers[i];
result += roman[i];
}
}

return result;
}

struct cmp {
cmp() {
char nums[7] = {'I', 'V', 'X', 'L', 'C', 'D', 'M'};
for (int i = 0; i < 7; ++i) {
map[nums[i]] = i;
}
}
bool operator()(char a, char b) {
return map[a] < map[b];
}

unordered_map<char, int> map;
};

int main() {
ifstream fin("preface.in");
ofstream fout("preface.out");

fin >> N;
map<char, int, cmp> mp;
for (int i = 1; i <= N; ++i) {
string num = intToRoman(i);
for (auto &c : num) {
mp[c]++;
}
}

for (map<char, int>::iterator iter = mp.begin(); iter != mp.end(); ++iter) {
fout << iter->first << " " << iter->second << endl;
}
}

USACO 2.1 Hamming Codes

#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>

using namespace std;

int main() {
ifstream fin("hamming.in");
ofstream fout("hamming.out");

int N, B, D;
fin >> N >> B >> D;
vector<int> result;
result.push_back(0);
int count = 1;
for (int i = 1; count < N; ++i) {
if (count == N) break;

bool ok(true);
for (auto &item : result) {
bitset<64> diff(i ^ item);
if (diff.count() < D) {
ok = false;
break;
}
}

if (ok) {
++count;
result.push_back(i);
}
}

count = 0;
for (int i = 0; i < result.size(); ++i) {
count++;
fout << result[i];
if ((count != 0 && count % 10 == 0) || count == result.size())
fout << endl;
else
fout << " ";
}

return 0;
}

USACO 2.1 Healthy Holsteins

Brutal force approach using bit set to speed up search.

#include <iostream>
#include <fstream>
#include <bitset>

using namespace std;

int V, vit[26], G, feedType[16][26], vc;
bitset<16> minbit(0);

int main() {
ifstream fin("holstein.in");
ofstream fout("holstein.out");

vc = 16;
fin >> V;
for(int i = 0; i < V; ++i)
fin >> vit[i];

fin >> G;
for(int i = 0; i < G; ++i)
for(int j=0 ; j < V; ++j)
fin >> feedType[i][j];

auto limit = 1 << G;
for(int i = 0; i < limit; ++i) {
int v[26] = {0};
bitset<16> bit(i);
for(int b = 0; b != G; ++b) {
if(bit[b]) {
for(int j = 0; j != V; ++j)
v[j] += feedType[b][j];
}
}

bool satisfy = true;
for(int j = 0; j < V; ++j) {
if(v[j] < vit[j]) {
satisfy = false;
break;
}
}

if(satisfy && int(bit.count()) < vc && bit.to_ulong() > minbit.to_ulong()) {
vc = static_cast<int>(bit.count());
minbit = bit;
}
}

fout << vc;
for(int i = 0; i < G; ++i) {
if(minbit[i])
fout << " " << i + 1;
}

fout << endl;

return 0;
}