Bee Problem
Preliminaries for Benelux Algorithm Programming Contest 2018
题意:
给出 n 行 m 列,“ # ” 表示障碍,求至少几个连通块加起来大于等于 h 。
思路:
BFS求连通块,记录每个连通块的大小,排序然后从大到小贪心。
Code:
#include <bits/stdc++.h>
using namespace std;
typedef pair<int, int> pii;
const int N = 1005;
int h, n, m; //蜂蜜数量 行数 列数
char mp[N][N];
bool vis[N][N];
//奇数行
int odd[2][6] = {0, 1, 1, 0, -1, -1, //x
1, 0, -1, -1, -1, 0}; //y
//偶数行
int even[2][6] = {0, 1, 1, 0, -1, -1, //x
1, 1, 0, -1, 0, 1}; //y
vector<int> cnt;
void bfs(int x, int y)
{
vis[x][y] = true;
int sum = 1;
queue<pii> q;
q.push(make_pair(x, y));
while (!q.empty())
{
pii now = q.front();
q.pop();
for (int i = 0; i < 6; i++)
{
int xx, yy;
if (now.first & 1) //odd
{
xx = now.first + odd[0][i];
yy = now.second + odd[1][i];
}
else //even
{
xx = now.first + even[0][i];
yy = now.second + even[1][i];
}
if (xx >= 1 && xx <= n && yy >= 1 && yy <= m && !vis[xx][yy] && mp[xx][yy] == '.')
{
sum++;
vis[xx][yy] = true;
q.push(make_pair(xx, yy));
}
}
}
cnt.push_back(sum);
}
int main()
{
#ifdef LOCAL_LIUZHIHAN
freopen("in.in", "r", stdin);
// freopen("out.out", "w", stdout);
#endif
ios::sync_with_stdio(false);
cin >> h >> n >> m;
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
cin >> mp[i][j];
for (int i = 1; i <= n; i++)
for (int j = 1; j <= m; j++)
if (!vis[i][j] && mp[i][j] == '.')
bfs(i, j);
sort(cnt.begin(), cnt.end());
int sum = 0, ans = 0;
for (int i = cnt.size() - 1; i >= 0; i--)
{
if (sum >= h)
break;
sum += cnt[i];
ans++;
}
cout << ans << endl;
return 0;
}