Datasets:

Modalities:
Image
Text
Formats:
parquet
Size:
< 1K
Tags:
code
Libraries:
Datasets
pandas
License:
File size: 1,945 Bytes
d3f4f72
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <algorithm>
#include <iostream>
#include <tuple>
#include <utility>
#include <vector>
using namespace std;

const int LIM = 1000002;

struct UnionFind {
  int N;
  vector<int> root, rank;
  vector<bool> 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<tuple<int, int, int>> A;

pair<int, int> 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<int, int> 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;
}