#include <vector>
#include <algorithm>
using namespace std;
int minimumInstructions(int N, int M, int K, vector<int> C, vector<int> A, vector<vector<int>> B) {
vector<vector<int>> color_to_workers(K);
for (int j = 0; j < M; ++j) {
for (int color : B[j]) {
color_to_workers[color].push_back(j);
}
}
vector<int> dp(M, 0);
vector<bool> can_start(N - M + 1, false);
for (int i = 0; i < N; ++i) {
vector<int> next_dp(M, 0);
for (int worker : color_to_workers[C[i]]) {
int prev_worker = (worker - 1 + M) % M;
next_dp[worker] = (i == 0) ? 1 : dp[prev_worker] + 1;
if (next_dp[worker] >= M) {
can_start[i - M + 1] = true;
}
}
dp = next_dp;
}
int count = 0;
int current_end = -1;
int next_reachable = -1;
int i = 0;
while (i <= N - M) {
bool found = false;
while (i <= N - M && i <= current_end + 1) {
if (can_start[i]) {
next_reachable = i + M - 1;
found = true;
}
i++;
}
if (!found || next_reachable <= current_end) return -1;
current_end = next_reachable;
count++;
if (current_end >= N - 1) return count;
}
return (current_end >= N - 1) ? count : -1;
}