|
#include <iostream> |
|
#include <vector> |
|
using namespace std; |
|
|
|
const int INF = (int)1e9; |
|
|
|
struct fenwick { |
|
vector<int> a, t; |
|
|
|
fenwick(int N) : a(N + 1), t(N + 1) {} |
|
|
|
int sum(int hi) const { |
|
int res = 0; |
|
for (; hi > 0; hi -= hi & -hi) { |
|
res += t[hi]; |
|
} |
|
return res; |
|
} |
|
|
|
void inc(int i, int x) { |
|
a[i] += x; |
|
for (; i < (int)t.size(); i += i & -i) { |
|
t[i] += x; |
|
} |
|
} |
|
|
|
int at(int i) const { return a[i]; } |
|
int sum(int lo, int hi) const { return sum(hi) - sum(lo - 1); } |
|
void set(int i, int x) { inc(i, x - a[i]); } |
|
}; |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
void do_swaps(vector<int> &L, vector<int> &H, int v1, int v2, int swaps) { |
|
L[v1] -= swaps; |
|
H[v1] += swaps; |
|
H[v2] -= swaps; |
|
L[v2] += swaps; |
|
} |
|
|
|
|
|
int strategy_a(vector<int> L, vector<int> H, int d) { |
|
|
|
|
|
int swap13 = min(min(L[0], H[2]), d / 4); |
|
do_swaps(L, H, 0, 2, swap13); |
|
d -= 4*swap13; |
|
|
|
int swap12 = min(min(L[0], H[1]), d / 2); |
|
do_swaps(L, H, 0, 1, swap12); |
|
d -= 2*swap12; |
|
int swap23 = min(min(L[1], H[2]), d / 2); |
|
do_swaps(L, H, 1, 2, swap23); |
|
d -= 2*swap23; |
|
return d != 0 ? INF : swap13 + swap12 + swap23; |
|
} |
|
|
|
|
|
int strategy_b(vector<int> L, vector<int> H, int d) { |
|
|
|
int swap13 = min(min(L[0], H[2]), d / 4 + (int)(d % 4 != 0)); |
|
do_swaps(L, H, 0, 2, swap13); |
|
d -= 4*swap13; |
|
|
|
int swap21 = min(min(L[1], H[0]), d < 0 ? (-d)/2 : 0); |
|
do_swaps(L, H, 1, 0, swap21); |
|
d += 2*swap21; |
|
int swap32 = min(min(L[2], H[1]), d < 0 ? (-d)/2 : 0); |
|
do_swaps(L, H, 2, 1, swap32); |
|
d += 2*swap32; |
|
return d != 0 ? INF : swap13 + swap21 + swap32; |
|
} |
|
|
|
long long solve() { |
|
int N, M; |
|
cin >> N >> M; |
|
fenwick T[]{fenwick(N), fenwick(N), fenwick(N)}; |
|
for (int i = 1, a; i <= N; i++) { |
|
cin >> a; |
|
T[--a].set(i, 1); |
|
} |
|
long long ans = 0; |
|
for (int i = 0, x, y, z; i < M; i++) { |
|
cin >> x >> y >> z; |
|
--y; |
|
for (int v : {0, 1, 2}) { |
|
T[v].set(x, v == y); |
|
} |
|
vector<int> L(3), H(3); |
|
int sumL = 0, sumH = 0; |
|
for (int v : {0, 1, 2}) { |
|
L[v] = T[v].sum(1, z); |
|
H[v] = T[v].sum(z + 1, N); |
|
sumL += (v + 1) * L[v]; |
|
sumH += (v + 1) * H[v]; |
|
} |
|
if (sumL == sumH) { |
|
continue; |
|
} |
|
if (sumL > sumH) { |
|
swap(sumL, sumH); |
|
L.swap(H); |
|
} |
|
int d = sumH - sumL; |
|
int swaps_a = strategy_a(L, H, d), swaps_b = strategy_b(L, H, d); |
|
int Q = min(swaps_a, swaps_b); |
|
ans += (Q == INF) ? -1 : Q; |
|
} |
|
return ans; |
|
} |
|
|
|
int main() { |
|
ios_base::sync_with_stdio(false); |
|
cin.tie(nullptr); |
|
int T; |
|
cin >> T; |
|
for (int t = 1; t <= T; t++) { |
|
cout << "Case #" << t << ": " << solve() << endl; |
|
} |
|
return 0; |
|
} |
|
|