USACO BRHS10A Problem 'codes' Analysis

by Damon Doucet

This problem can be solved with a few arrays (if you consider one of the arrays being the output string). One array contains the characters that need to be replaced; one array contains the characters to replace those with; the final array, as aforementioned, contains the output.

We loop through the input string, and then check, for each character, if it needs to be replaced, then replace its counterpart in the output string with the character it should be replaced by.

Here's my solution:

#include <fstream>
#include <string>
using namespace std;

int R;
char C[35], W[35];

ifstream fin("codes.in");
ofstream fout("codes.out");

int main() {
	string M, out;
	fin >> R;
	for (int i = 0; i < R; i++) {
		fin >> C[i] >> W[i];
	}

	getline(fin, M); //trash
	getline(fin, M);
	out = M;

	for (int i = 0; i < M.length(); i++) {
		for (int j = 0; j < R; j++) {
			if (C[j] == M.at(i))
				out.at(i) = W[j];
		}
	}
	fout << out << endl;

	return 0;
}