import std.stdio;
import std.ascii;
import std.range;
import std.array;
import std.functional;
import std.algorithm;
import std.conv;
import std.container;
import std.math;
import std.numeric;
import std.string;
import std.c.string;
import std.random;
import std.regex;
import std.typecons;

struct STAMP {
    int H, W;
}

int N;
STAMP[] S;
string[] F;
int[] masks;

void input() {
    scanf("%d\n", &N);
    S = new STAMP[N];
    foreach (i; 0 .. N) {
        int h, w; scanf("%d %d\n", &h, &w);
        S[i] = STAMP(h, w);
    }
    F = new string[4];
    foreach (i; 0 .. 4) {
        F[i] = readln.chomp;
    }

    masks.destroy;
    foreach (s; S) {
        for (int y = -3; y < 4; y++) {
            for (int x = -3; x < 4; x++) {
                int sy = max(0, y),
                    gy = min(y + s.H, 4);
                int sx = max(0, x),
                    gx = min(x + s.W, 4);
                int mask = 0;
                for (int i = sy; i < gy; i++) {
                    for (int j = sx; j < gx; j++) {
                        mask |= 1 << (i * 4 + j);
                    }
                }
                masks ~= mask;
            }
        }
    }
    masks = masks.sort.uniq.array;
}

void solve() {
    int init = 0;
    bool[int] used;
    used[init] = true;
    struct P {
        int state, dist;
        string toString() const {
            return format("P(%016b, %d)", state, dist);
        }
    }
    DList!P Q;
    Q.insert(P(init, 0));
    while (!Q.empty) {
        auto cur = Q.front; Q.removeFront;
        //writeln(cur);
        foreach (c; "RGB") {
            foreach (mask; masks) {
                int next = cur.state;
                foreach (int i; 0 .. 16) {
                    if (!(mask & (1 << i))) continue;
                    int y = i / 4,
                        x = i % 4;
                    if (c == F[y][x]) {
                        next |= (1 << i);
                    } else {
                        next &= ~(1 << i);
                    }
                }
                if (next == (1 << 16) - 1) {
                    writeln(cur.dist + 1);
                    return;
                }
                if (next in used) continue;
                Q.insert(P(next, cur.dist + 1));
                used[next] = true;
            }
        }
    }
    assert(false);
}

void main() {
    input;
    solve;
}