题解
2023-08-27 16:25:39
发布于:广东
4阅读
0回复
0点赞
沙发!
#include <bits/stdc++.h>
using namespace std;
#define read cin
#define written cout
vector<pair<int, int>> neighbors(int r, int c) {
return {{r + 1, c}, {r - 1, c}, {r, c + 1}, {r, c - 1}};
}
int main() {
int side_len;
read >> side_len;
vector<vector<int>> grid(side_len, vector<int>(side_len));
for (int r = 0; r < side_len; r++) {
for (int c = 0; c < side_len; c++) { read >> grid[r][c]; }
}
vector<vector<int>> regions(side_len, vector<int>(side_len));
vector<vector<pair<int, int>>> region_cells;
int one_biggest = 0;
vector<vector<bool>> visited(side_len, vector<bool>(side_len));
for (int r = 0; r < side_len; r++) {
for (int c = 0; c < side_len; c++) {
if (visited[r][c]) { continue; }
int curr_region = region_cells.size();
vector<pair<int, int>> contained;
vector<pair<int, int>> frontier{{r, c}};
visited[r][c] = true;
while (!frontier.empty()) {
pair<int, int> curr = frontier.back();
frontier.pop_back();
contained.push_back(curr);
regions[curr.first][curr.second] = curr_region;
for (const auto &[nr, nc] :
neighbors(curr.first, curr.second)) {
if (0 <= nr && 0 <= nc && nr < side_len && nc < side_len &&
!visited[nr][nc] && grid[nr][nc] == grid[r][c]) {
visited[nr][nc] = true;
frontier.push_back({nr, nc});
}
}
}
one_biggest = std::max(one_biggest, (int)contained.size());
region_cells.push_back(contained);
}
}
vector<std::set<int>> adj_regions(region_cells.size());
for (const vector<pair<int, int>> ® : region_cells) {
for (const auto &[r, c] : reg) {
for (const auto &[nr, nc] : neighbors(r, c)) {
if (0 <= nr && 0 <= nc && nr < side_len && nc < side_len &&
regions[nr][nc] != regions[r][c]) {
adj_regions[regions[r][c]].insert(regions[nr][nc]);
}
}
}
}
auto region_id = [&](int r) {
return grid[region_cells[r][0].first][region_cells[r][0].second];
};
std::map<pair<int, int>, std::set<int>> seen;
int two_biggest = one_biggest;
for (int r1 = 0; r1 < region_cells.size(); r1++) {
for (int r2 : adj_regions[r1]) {
pair<int, int> valid{region_id(r1), region_id(r2)};
if (valid.first > valid.second) {
std::swap(valid.first, valid.second);
}
if (seen[valid].count(r1)) { continue; }
int two_size = 0;
vector<int> frontier{r1};
vector<bool> curr_vis(region_cells.size());
curr_vis[r1] = true;
while (!frontier.empty()) {
int curr = frontier.back();
frontier.pop_back();
two_size += region_cells[curr].size();
seen[valid].insert(curr);
for (int nr : adj_regions[curr]) {
int nid = region_id(nr);
if (!curr_vis[nr] &&
(valid.first == nid || valid.second == nid)) {
curr_vis[nr] = true;
frontier.push_back(nr);
}
}
}
two_biggest = max(two_biggest, two_size);
}
}
written << one_biggest << '\n' << two_biggest << endl;
}
全部评论 1
抢到评论沙发
2024-05-31 来自 广东
1
有帮助,赞一个