#include "paint.h"
#include <bits/stdc++.h>
using namespace std;
int minimumInstructions(int n, int m, int k, vector<int> c, vector<int> a, vector<vector<int>> b){
bool st[n];
memset(st, 0, sizeof st);
vector<set<int>> cl(k);
unordered_map<int, bool> mp[m];
for(int i = 0;i<m;i++){
for(int j = 0;j<a[i];j++){
cl[b[i][j]].insert(i);
mp[i][b[i][j]] = 1;
}
}
for(int i = 0;i<n - m + 1;i++){
bool ok = 1;
vector<int> cand;
for(auto x : cl[c[i]]) cand.push_back(x);
for(int j = 1;j<m;j++){
vector<int> ncd;
for(auto x : cand){
if(mp[(x + j) % m][c[i + j]]){
ncd.push_back(x);
}
}
if(ncd.empty()){
ok = 0;
break;
}
cand = ncd;
}
st[i] = ok;
}
int ans = 0, id = 0, pv = 0;
while(id != n){
if(st[id]){
pv = id;
++ans;
id += m;
}else{
--id;
if(id < 0 || id == pv) return -1;
}
}
return ans;
}