|
| 1 | +```cpp |
| 2 | +#include <bits/stdc++.h> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +const int dx[4] = {1,0,-1,0}; |
| 6 | +const int dy[4] = {0,1,0,-1}; |
| 7 | + |
| 8 | +int R; |
| 9 | + |
| 10 | +vector<pair<int, int>> office() { |
| 11 | + int N, M, X, Y; |
| 12 | + cin>>M>>N>>Y>>X; |
| 13 | + Y--, X--; |
| 14 | + |
| 15 | + int root[250000]{}; |
| 16 | + int cnt[250000]{}; |
| 17 | + iota(root, root+N*M, 0); |
| 18 | + fill(cnt, cnt+N*M, 1); |
| 19 | + function<int(int)> find = [&](int x) -> int { return x == root[x] ? x : root[x] = find(root[x]); }; |
| 20 | + |
| 21 | + bitset<250000> vis; |
| 22 | + vis[X*M+Y] = 1; |
| 23 | + |
| 24 | + vector<tuple<int, int, int>> infos; |
| 25 | + for(int i=0;i<N;i++) for(int j=0;j<M;j++) { |
| 26 | + int a; |
| 27 | + cin>>a; |
| 28 | + infos.emplace_back(a,i,j); |
| 29 | + } |
| 30 | + |
| 31 | + sort(infos.begin(), infos.end()); |
| 32 | + vector<pair<int, int>> events; |
| 33 | + for(int i=0;i<infos.size();) { |
| 34 | + auto [cc,aa,bb] = infos[i]; |
| 35 | + int j = i; |
| 36 | + while(j<infos.size() && get<0>(infos[j]) == cc) { |
| 37 | + auto [c,a,b] = infos[j]; |
| 38 | + vis[a*M+b] = 1; |
| 39 | + for(int k=0;k<4;k++) { |
| 40 | + int aa = a+dx[k], bb = b+dy[k]; |
| 41 | + if(aa<0 || aa>=N || bb<0 || bb>=M || !vis[aa*M+bb]) continue; |
| 42 | + int x = find(a*M+b), y = find(aa*M+bb); |
| 43 | + if(x == y) continue; |
| 44 | + cnt[y] += cnt[x]; |
| 45 | + root[x] = y; |
| 46 | + } |
| 47 | + j++; |
| 48 | + } |
| 49 | + i = j; |
| 50 | + events.emplace_back(cc, cnt[find(X*M+Y)]); |
| 51 | + } |
| 52 | + |
| 53 | + return events; |
| 54 | +} |
| 55 | + |
| 56 | +int main(){ |
| 57 | + cin.tie(0)->sync_with_stdio(0); |
| 58 | + |
| 59 | + cin>>R; |
| 60 | + vector<pair<int, int>> res1 = office(); |
| 61 | + vector<pair<int, int>> res2 = office(); |
| 62 | + |
| 63 | + int ans = 2e9 + 1; |
| 64 | + for(auto [c,v] : res1) if(v >= R) { |
| 65 | + ans = min(ans, c); |
| 66 | + break; |
| 67 | + } |
| 68 | + for(auto [c,v] : res2) if(v >= R) { |
| 69 | + ans = min(ans, c); |
| 70 | + break; |
| 71 | + } |
| 72 | + for(int i=0,j=res2.size()-1;i<res1.size();i++) { |
| 73 | + if(res1[i].second + res2[j].second >= R) { |
| 74 | + while(j>=0 && res1[i].second + res2[j].second >= R) j--; |
| 75 | + j++; |
| 76 | + } |
| 77 | + if(res1[i].second + res2[j].second >= R) { |
| 78 | + ans = min(ans, res1[i].first + res2[j].first); |
| 79 | + } |
| 80 | + } |
| 81 | + cout<<ans; |
| 82 | + |
| 83 | +} |
| 84 | +``` |
0 commit comments