#!/usr/bin/perl -w

use strict;

my $line = <>;
chomp $line;
my ($x, $y, $cols, $width) = split / /, $line;
print "P3 $x $y\n256\n";

my %map;
for (my $i = 0; $i < $cols; $i++) {
	$line = <>;
	$line =~ m/^(..) c #(.*)/;
	$map{$1} = expand($2);
}

for (my $i = 0; $i < $y; $i++) {
	$line = <>;
	for (my $j = 0; $j < $x; $j++) {
		my $code = substr $line, $j * 2, 2;
		die "<$code>" unless exists $map{$code};
		print $map{$code}, "  ";
	}
	print "\n";
}
	
sub expand {
	my $arg = shift;
	my ($r, $g, $b) = ($arg =~ m/(..)(..)(..)/);
	$r = hex($r);
	$g = hex($g);
	$b = hex($b);
	return sprintf ("%3d %3d %3d", $r, $g, $b);
}
