#include<bits/stdc++.h>
#define for0(i, n) for(int i = 0; i < (n); i++)
#define for1(i, n) for(int i = 1; i <= (n);i++)
#define puts(x) cout << (x) << "\n"
using namespace std;
int si, sj, t[60][60], p[60][60], M;
bool b1[50 * 51];
int score(string s) {
	int xs = si, ys = sj, r = p[xs][ys];
	for (char c : s) {
		if (c == 'U')xs--;
		if (c == 'D')xs++;
		if (c == 'L')ys--;
		if (c == 'R')ys++;
		r += p[xs][ys];
	}
	return r;
}
int main() {
    srand((unsigned)time(NULL));
	cin >> si >> sj; si++; sj++; b1[2525] = 1;
	for0(i, 52)for0(j, 52) {
		if (i * j == 0 || i == 51 || j == 51)t[i][j] = 2525;
		else { cin >> t[i][j]; M = max(M, t[i][j]); }
	}
	for1(i, 50)for1(j, 50)cin >> p[i][j];	
	string s1 = ""; int v1 = score(s1), ti = clock();
	while(clock() - ti <= 1800000) {
		string sp = "";
		int xi = si, yi = sj;
		while (1) {
			b1[t[xi][yi]] = 1;
			int tm = b1[t[xi - 1][yi]] + b1[t[xi + 1][yi]] + b1[t[xi][yi - 1]] + b1[t[xi][yi + 1]];
			if (tm == 4)break;
			int ri = rand() % (4 - tm);
			if (b1[t[xi - 1][yi]] == 0) { if (ri == 0) { sp += 'U'; xi--; } ri--; }
			if (b1[t[xi + 1][yi]] == 0) { if (ri == 0) { sp += 'D'; xi++; } ri--; }
			if (b1[t[xi][yi - 1]] == 0) { if (ri == 0) { sp += 'L'; yi--; } ri--; }
			if (b1[t[xi][yi + 1]] == 0) { if (ri == 0) { sp += 'R'; yi++; } ri--; }
		}
		int vi = score(sp);
		if (vi > v1) {
			s1 = sp; v1 = vi;
		}
		for0(i, M)b1[i] = 0;
	}
	puts(s1);
}
#include <vector>
#include <stdio.h>
#include <algorithm>

int n, fa[100005], head[100005], cnt, dp[100005], size[100005];
struct edge { int to, nxt; } g[100005];

inline void add_edge(int f, int t) {
	g[++cnt].to = t;
	g[cnt].nxt = head[f];
	head[f] = cnt;
}

void dfs(int u) {
	dp[u] = 1; size[u] = 1;
	std::vector<int> vs;
	int side = 1, sum = 0;
	for (int i = head[u]; i; i = g[i].nxt) {
		dfs(g[i].to);
		size[u] += size[g[i].to];
		if (size[g[i].to] & 1) vs.push_back(dp[g[i].to]);
		else if (dp[g[i].to] >= 0) sum += dp[g[i].to];
		else dp[u] += dp[g[i].to];
	}
	std::sort(vs.begin(), vs.end());
	for (int val : vs) {
		dp[u] += side * val;
		side = -side;
	}
	dp[u] += side * sum;
}

int main() {
	scanf("%d", &n);
	for (int i = 2; i <= n; ++i) scanf("%d", fa + i), add_edge(fa[i], i);
	dfs(1);
	printf("%d\n", (n + dp[1]) >> 1);
	return 0;
} 