题目链接:奶牛选美
题目分析:
0.考察知识点:Flood Fill
1.先求一遍Flood Fill 存一下两个连通块。
2.依次枚举两个连通块中的点。求一下曼哈顿距离,求min值即可。O(n^2)
3.为什么求曼哈顿距离即可?
证明:假设a,b两个点是我们所求的最优解。那么他们之间一定没有障碍点。如果有障碍点的话,说明他们之间的距离还可以更小。故最优解中间没有障碍点,只需要求一下曼哈顿距离即可。
code:
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#define x first
#define y second
using namespace std;
typedef pair<int, int> PII;
const int N = 55;
int n, m;
char g[N][N];
vector<PII> points[2];
int dx[4] = {-1, 0, 1, 0}, dy[4] = {0, 1, 0, -1};
void dfs(int x, int y, vector<PII>& ps)
{
g[x][y] = '.';
ps.push_back({x, y});
for(int i = 0; i < 4; i ++)
{
int a = x + dx[i], b = y + dy[i];
if(a >= 0 && a < n && b >= 0 && b < m && g[a][b] == 'X')
dfs(a, b, ps);
}
}
int main()
{
cin >> n >> m;
for(int i = 0; i < n; i ++) cin >> g[i];
for(int i = 0, k = 0; i < n; i ++)
for(int j = 0; j < m; j ++)
{
if(g[i][j] == 'X')
dfs(i, j, points[k ++]);
}
int res = 1e8;
for(auto& a : points[0])
for(auto& b : points[1])
res = min(res, abs(a.x - b.x) + abs(a.y - b.y) - 1);
cout << res << endl;
return 0;
}
总结:
1.曼哈顿距离计算:
c=|x1 - x2| + |y1 - y2|。
2.用auto 遍历 STL容器:
2.1 vector<int> line={1,2,3,4,5,6,7,8,9};
for (auto lin : line) {
cout << lin;
}
2.2 遍历字符串:
string a = asd
for(auto c : a)
cout << c << " ";
结果:a s d
//带&的auto
string a = asd
for(auto& c : a)
{
c = '1';
}
cout << a;
结果:111