#include <iostream>
#include <sstream>
#include <string>
#include <algorithm>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cassert>

using namespace std;

#define FOR(i,k,n) for(int i=(k); i<(int)(n); ++i)
#define REP(i,n) FOR(i,0,n)
#define FORIT(i,c) for(__typeof((c).begin())i=(c).begin();i!=(c).end();++i)

template<class T> void debug(T begin, T end){ for(T i = begin; i != end; ++i) cerr<<*i<<" "; cerr<<endl; }
inline bool valid(int x, int y, int W, int H){ return (x >= 0 && y >= 0 && x < W && y < H); }

typedef long long ll;
const int INF = 100000000;
const double EPS = 1e-8;
const int MOD = 1000000007;
int dx[8] = {1, 0, -1, 0, 1, -1, -1, 1};
int dy[8] = {0, 1, 0, -1, 1, 1, -1, -1};
int N;
int score[5];
void output(int a[5][5]){
  REP(i, 5){
    REP(j, 5) printf("%d ", a[i][j]);
    printf("\n");
  }
}
int point(int a[5][5]){
  int bonus = 1;
  int res = 0;
  while(true){
    bool del[5][5] = {};
    bool update = false;
    REP(y, 5) for(int i = 2; i < 5; i++) {
      if(a[y][i-2] == a[y][i-1] && a[y][i-1] == a[y][i] && a[y][i] != 0){
        del[y][i-2] = del[y][i-1] = del[y][i] = true;
        update = true;
      }
    }
    REP(x, 5) for(int i = 2; i < 5; i++) {
      if(a[i-2][x] == a[i-1][x] && a[i-1][x] == a[i][x] && a[i][x] != 0){
        del[i-2][x] = del[i-1][x] = del[i][x] = true;
        update = true;
      }
    }
    if(!update) break;
    REP(y, 5)REP(x, 5) if(del[y][x]){
      res += score[a[y][x] - 1] * bonus;
      a[y][x] = 0;
    }
    //output(a);
    //printf("v\n");
    REP(x, 5){
      queue<int> que;
      for(int y = 4; y >= 0; y--)if(a[y][x] != 0){
        que.push(a[y][x]);
      }
      for(int y = 4; y >= 0; y--){
        if(que.empty()){
          a[y][x] = 0;
        }else{
          a[y][x] = que.front();
          que.pop();
        }
      }
    }
    //output(a);
    //printf("\n\n");
    bonus += 1;
  }
  return res;
}
int dfs(int a[5][5], int k, int x, int y){
  int res = 0;
  int tmp[5][5];
  REP(i, 5)REP(j, 5) tmp[i][j] = a[i][j];
  res = point(tmp);
  if(k == N) return res;
  REP(r, 4){
    int nx = x + dx[r];
    int ny = y + dy[r];
    if(valid(nx, ny, 5, 5)){
      swap(a[y][x], a[ny][nx]);
      res = max(res, dfs(a, k + 1, nx, ny));
      swap(a[y][x], a[ny][nx]);
    }
  }
  return res;
}
int main(){
  while(cin >> N && N != -1){
    int a[5][5];
    REP(i, 5)REP(j, 5) cin >> a[i][j];
    REP(i, 5) cin >> score[i];
    int ans = 0;
    REP(y, 5)REP(x, 5) ans = max(ans, dfs(a, 0, x, y));
    cout << ans << endl;
  }
  return 0;
}