原题链接:0702-最短路专题 - Virtual Judge
题目描述:
看完题,稍微有点懵逼,但是能读懂的是最大容量就等于所有连起来的地点的边权总和。
样例就让你很明白的看出你要找出一块连起来的地方,就可以想到连通块+bfs的强强解法(bushi
思路解析:
整体思路呢就是先读进去数据,利用bfs找出一个完整的连通块,顺便呢,用sum记录每个点上的值相加之和,最后与上一个连通块的ans进行比较,选择max(sum,ans),再进行下一次搜索。
一点小坑就是,本题有多组数据,而且连通块走完要注意将其赋值为-1,避免下次连通块是再访问。
#include <iostream>
#include <queue>
const int N = 1005;
const int dir[][2] = {
{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int a[N][N];
int n, m;
int bfs(int x, int y) {
std::queue<std::pair<int, int> > q;//运用了pair数组,来代替了有多个数据的Node数组
q.push(std::make_pair(x, y));
int res = a[x][y];//记录每个点的值之和
a[x][y] = 0;
while (!q.empty()) {//正常的bfs
std::pair<int, int> f = q.front();
q.pop();
for (int i = 0; i < 4; i++) {
int xx = f.first + dir[i][0];
int yy = f.second + dir[i][1];
if (xx > 0 && yy > 0 && xx <= n && yy <= m && a[xx][yy] != 0) {//判断特殊临界点
res += a[xx][yy];
a[xx][yy] = 0;//避免下次再访问到
q.push(std::make_pair(xx, yy));
}
}
}
return res;
}
void solve() {
std::cin >> n >> m;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
std::cin >> a[i][j];
}
}
int ans = 0;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (a[i][j] != 0) {
int res = bfs(i, j);
ans = std::max(ans, res);与之前的答案取一个最大值
}
}
}
std::cout << ans << '\n';
}
int main() {
int T;
std::cin >> T;
while (T--) {
solve();
}
return 0;
}
总结:整体的思路就是一个连通块+bfs,还是比较好想,码好bfs、处理好细节就可以AC,及Accepted啦!
创作不易,请勿白嫖啊www!麻烦给个三连+关注就好呀,谢!