#include<iostream> usingnamespace std; constint MAXN = 20 + 5; constint MAXT = 1e4; structworkpiece{ int machine[MAXN], time[MAXN]; }wp[MAXN]; int order[MAXN * MAXN], finish[MAXN], now_op[MAXN], machine[MAXN][MAXT]; intmain(){ int n, m, ans; cin >> m >> n; for (int i = 1; i <= n * m; i++) cin >> order[i]; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> wp[i].machine[j]; for (int i = 1; i <= n; i++) for (int j = 1; j <= m; j++) cin >> wp[i].time[j];
for (int i = 1; i <= n * m; i++){ int op = order[i]; int step = ++now_op[op]; int machine_now = wp[op].machine[step]; int time_needed = wp[op].time[step];
int t = finish[op] + 1; while(true){ bool flag = false; for (int j = t; j <= t + time_needed - 1; j++){ if (machine[machine_now][j]) break; if (j == t + time_needed - 1) flag = true; } if (flag) break; else t++; } for (int j = t; j <= t + time_needed - 1; j++) machine[machine_now][j] = true; finish[op] = t + time_needed - 1; ans = max(ans, finish[op]); } cout << ans; }