|
#include <cassert> |
|
#include <iostream> |
|
#include <vector> |
|
using namespace std; |
|
|
|
using LL = long long; |
|
|
|
struct fenwick { |
|
vector<LL> a, t; |
|
|
|
fenwick(int N) : a(N + 1), t(N + 1) {} |
|
|
|
LL sum(int hi) const { |
|
LL res = 0; |
|
for (; hi > 0; hi -= hi & -hi) { |
|
res += t[hi]; |
|
} |
|
return res; |
|
} |
|
|
|
void inc(int i, LL x) { |
|
a[i] += x; |
|
for (; i < (int)t.size(); i += i & -i) { |
|
t[i] += x; |
|
} |
|
} |
|
|
|
LL at(int i) const { return a[i]; } |
|
LL sum(int lo, int hi) const { return sum(hi) - sum(lo - 1); } |
|
void set(int i, LL x) { inc(i, x - a[i]); } |
|
}; |
|
|
|
template <typename Predicate> |
|
int binary_search_last_true(int lo_incl, int hi_excl, Predicate pred) { |
|
int mid, lo = lo_incl, hi = hi_excl - 1; |
|
while (lo < hi) { |
|
mid = lo + (hi - lo + 1) / 2; |
|
if (pred(mid)) { |
|
lo = mid; |
|
} else { |
|
hi = mid - 1; |
|
} |
|
} |
|
return pred(lo) ? lo : hi_excl; |
|
} |
|
|
|
LL solve() { |
|
int N, M; |
|
cin >> N >> M; |
|
auto rev = [=](int i) -> int { return N - i + 1; }; |
|
fenwick Tv_fwd(N), Ti_fwd(N), Tv_rev(N), Ti_rev(N); |
|
for (int i = 1, a; i <= N; i++) { |
|
cin >> a; |
|
Tv_fwd.set(i, a == 2); |
|
Ti_fwd.set(i, a == 2 ? i : 0); |
|
Tv_rev.set(rev(i), a == 2); |
|
Ti_rev.set(rev(i), a == 2 ? i : 0); |
|
} |
|
LL ans = 0; |
|
for (int i = 0, x, y, z; i < M; i++) { |
|
cin >> x >> y >> z; |
|
Tv_fwd.set(x, y == 2); |
|
Ti_fwd.set(x, y == 2 ? x : 0); |
|
Tv_rev.set(rev(x), y == 2); |
|
Ti_rev.set(rev(x), y == 2 ? x : 0); |
|
int L2cnt = Tv_fwd.sum(1, z), H2cnt = Tv_fwd.sum(z + 1, N); |
|
int sumL = 1 * (z - L2cnt) + 2 * L2cnt; |
|
int sumH = 1 * (N - z - H2cnt) + 2 * H2cnt; |
|
if (sumL == sumH) { |
|
continue; |
|
} |
|
auto getQ = [&]( |
|
const fenwick &Tv, const fenwick &Ti, int d, int z, bool is_rev |
|
) -> LL { |
|
int req2s = d / 2, tgt2s = Tv.sum(1, z) + req2s; |
|
if ( |
|
d % 2 == 1 || |
|
tgt2s > z || |
|
req2s > Tv.sum(z + 1, N) |
|
) { |
|
return -1; |
|
} |
|
|
|
|
|
|
|
int s = binary_search_last_true(1, z + 1, [&](int s) { |
|
|
|
|
|
|
|
return Tv.sum(1, s - 1) + (z - s + 1) >= tgt2s; |
|
}); |
|
assert(s <= z); |
|
int c = z - s + 1; |
|
|
|
|
|
int t = 1 + binary_search_last_true(s, N + 1, [&](int t) { |
|
|
|
|
|
return Tv.sum(s, t) < c; |
|
}); |
|
assert(t <= N); |
|
|
|
if (is_rev) { |
|
return (LL)c*(rev(s) + rev(z))/2 - Ti.sum(s, t); |
|
} |
|
return Ti.sum(s, t) - (LL)c*(s + z)/2; |
|
}; |
|
if (sumL < sumH) { |
|
ans += getQ(Tv_fwd, Ti_fwd, sumH - sumL, z, false); |
|
} else { |
|
ans += getQ(Tv_rev, Ti_rev, sumL - sumH, rev(z) - 1, true); |
|
} |
|
} |
|
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; |
|
} |
|
|