#include "bits/stdc++.h"
#include<unordered_map>
#include<unordered_set>
#pragma warning(disable:4996)
using namespace std;
using ld = long double;
const ld eps = 1e-9;

//// < "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\a.txt" > "d:\d_download\visual studio 2015\projects\programing_contest_c++\debug\b.txt"

vector<int>ss(5);
void  fall(vector<vector<int>>&field) {
	for (int t = 0; t < 5; ++t) {
		for (int y = 4; y > 0; --y) {
			for (int x = 0; x < 5; ++x) {
				if (field[y][x] == 0 && field[y - 1][x]) {
					swap(field[y][x], field[y - 1][x]);
				}
			}
		}
	}
}
int getscore(vector<vector<int>>field) {
	int bonus = 1;
	int ans = 0;
	int num = 10;
	while (num--) {

		vector<vector<int>>del(5, vector<int>(5));
		{
			for (int x = 0; x < 5; ++x) {
				for (int u = 0; u < 3; ++u) {
					int c = field[u][x];
					if (!c)continue;
					int num = 0;
					for (int y = u; y < 5; ++y) {
						if (field[y][x] == c) {
							num++;
						}
						else {
							break;
						}
					}
					if (num >= 3) {
						for (int y = u; y < u + num; ++y) {
							del[y][x] = true;
						}
					}
				}
			}
			for (int y = 0; y < 5; ++y) {
				for (int l = 0; l < 3; ++l) {
					int c = field[y][l];
					if (!c)continue;
					int num = 0;
					for (int x = l; x < 5; ++x) {
						if (field[y][x] == c) {
							num++;
						}
						else {
							break;
						}
					}
					if (num >= 3) {
						for (int x = l; x < l + num; ++x) {
							del[y][x] = true;
						}
					}
				}
			}
		}
		for (int y = 0; y < 5; ++y) {
			for (int x = 0; x < 5; ++x) {
				if (del[y][x]) {
					ans += ss[field[y][x]-1] * bonus;
					field[y][x] = 0;
				}
			}
		}
		fall(field);

		bonus++;
	}
	return ans;
}
int dx[4] = { -1,0,1,0 };
int dy[4] = { 0,1,0,-1 };
int solve(vector<vector<int>>field, int rest,int x,int y) {
	int ans = getscore(field);
	if (rest) {
		for (int way = 0; way < 4; ++way) {
			int nx = x + dx[way];
			int ny = y + dy[way];
			if (nx >= 0 && nx < 5 && ny >= 0 && ny < 5) {
				swap(field[y][x], field[ny][nx]);
				ans = max(ans, solve(field, rest - 1, nx, ny));
				swap(field[y][x], field[ny][nx]);
			}
		}
	}
	return ans;
}

int main() {
	while (1) {
		int N; cin >> N;
		if (N == -1)break;
		vector<vector<int>>field(5, vector<int>(5));
		for (int i = 0; i < 5; ++i) {
			for (int j = 0; j < 5; ++j) {
				int a; cin >> a; field[i][j] = a;
			}
		}
		for (int i = 0; i < 5; ++i) {
			cin >> ss[i];
		}
		int ans = 0;
		for (int i = 0; i < 5; ++i) {
			for (int j = 0; j < 5; ++j) {
				ans = max(ans, solve(field, N, i, j));
			}
		}
		cout << ans << endl;
	}
	return 0;
}