Bee Problem(bfs 连通块 + 贪心)

Bee Problem

Preliminaries for Benelux Algorithm Programming Contest 2018

B - Bee Problem

题意:

给出 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;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值