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
| #include <bits/stdc++.h>
#define USE_CPPIO() ios_base::sync_with_stdio(0); cin.tie(0)
using namespace std;
int n, m, total, dsu[1000010];
int dx[4] = {0, 0, 1, -1};
int dy[4] = {1, -1, 0, 0};
struct Point {
int x, y, id, height;
};
vector<Point> vp;
bool cmp(Point a, Point b) {
return a.height > b.height;
}
int Find(int t) {
if(t == -1) return -1;
if(dsu[t] == t) return t;
return dsu[t] = Find(dsu[t]);
}
void add(int idx) {
int id = vp[idx].id;
dsu[id] = id;
++total;
for(int i = 0; i < 4; ++i) {
int x = vp[idx].x + dx[i];
int y = vp[idx].y + dy[i];
if(x >= 0 && x < n && y >= 0 && y < m) {
int id2 = x * m + y;
int root_id2 = Find(id2);
if(root_id2 == -1) continue;
if(root_id2 != id) {
--total;
dsu[root_id2] = id;
}
}
}
}
int main() {
USE_CPPIO();
int T;
cin >> T;
while(T--) {
cin >> n >> m;
vp.clear();
vector<int> h;
for(int i = 0; i < n; ++i) {
for(int j = 0; j < m; ++j) {
int t;
cin >> t;
Point p = {i, j, i * m + j, t};
vp.push_back(p);
dsu[i * m + j] = -1;
}
}
sort(vp.begin(), vp.end(), cmp);
int q;
cin >> q;
for(int i = 0; i < q; ++i) {
int t;
cin >> t;
h.push_back(t);
}
int idx = 0;
total = 0;
for(int i = h.size() - 1; i >= 0; --i) {
while(idx < vp.size() && h[i] < vp[idx].height)
add(idx++);
h[i] = total;
}
for(auto i : h) cout << i << " ";
cout << endl;
}
return 0;
}
|