#include #include #include #include #include using namespace std; const int LIM = 1000002; struct UnionFind { int N; vector root, rank; vector hasR; UnionFind(int _N): N(_N), root(_N), rank(_N, 0), hasR(_N, false) { for (int i = 0; i < N; i++) { root[i] = i; } } int find(int i) { if (root[i] != i) { root[i] = find(root[i]); } return root[i]; } void merge(int i, int j) { i = find(i); j = find(j); if (i == j) { return; } if (rank[i] > rank[j]) { swap(i, j); } root[i] = j; hasR[j] = hasR[j] || hasR[i]; if (rank[i] == rank[j]) { rank[j]++; } } }; int R, C, N; int H[LIM]; vector> A; pair solve() { A.clear(); // Input. cin >> R >> C; N = R * C; for (int i = 0, j; i < N; i++) { cin >> H[i]; if ((j = i - C) >= 0) { // Up. A.emplace_back(-min(H[i], H[j]), i, j); } if (i % C > 0 && (j = i - 1) >= 0) { // Left. A.emplace_back(-min(H[i], H[j]), i, j); } } for (int i = 0, s; i < N; i++) { cin >> s; A.emplace_back(-s, -1, i); } // Process edges/samples in non-increasing order of elevation. UnionFind U(N); sort(A.begin(), A.end()); pair ans{0, 0}; for (const auto &t : A) { int h = -get<0>(t), a = get<1>(t), b = get<2>(t); if (a < 0) { // Sample. if (H[b] <= h) { // Impossible to collect. continue; } ans.first++; // Collect it. b = U.find(b); if (!U.hasR[b]) { // Add new robot if necessary. U.hasR[b] = true; ans.second++; } continue; } U.merge(a, b); // Edge. } return ans; } int main() { int T; cin >> T; for (int t = 1; t <= T; t++) { auto ans = solve(); cout << "Case #" << t << ": " << ans.first << " " << ans.second << endl; } return 0; }