Rabbit House- Google Kick Start 2021 Round A

Google Kick Start 2021 Round A: Rabbit House

Barbara got really good grades in school last year, so her parents decided to gift her with a pet rabbit. She was so excited that she built a house for the rabbit, which can be seen as a 2D grid with R rows and C columns.
Rabbits love to jump, so Barbara stacked several boxes on several cells of the grid. Each box is a cube with equal dimensions, which match exactly the dimensions of a cell of the grid.
However, Barbara soon realizes that it may be dangerous for the rabbit to make jumps of height greater than 1 box, so she decides to avoid that by making some adjustments to the house. For every pair of adjacent cells, Barbara would like that their absolute difference in height be at most 1 box. Two cells are considered adjacent if they share a common side.
As all the boxes are superglued, Barbara cannot remove any boxes that are there initially, however she can add boxes on top of them. She can add as many boxes as she wants, to as many cells as she wants (which may be zero). Help hew determine what is the minimum total number of boxes to be added so that the rabbit’s house is safe.

题目大意

芭芭拉给她的兔子盖了一栋R × \times ×C的方格房间(1 ≤ \leq R,C ≤ \leq 300),其中她已经在某些方格上摆上了Gi,j个木盒(1 ≤ \leq Gi,j ≤ \leq 2 × \times × 106) 。为了保护兔子的安全,她希望通过在某些方块上添加木盒的方式,使得所有相邻的方格木盒数差距不超过1。求总共最少需要添加的木盒数。

题目思路

显然,在任一时刻,方阵中木盒数最多的方格都不需要添加木盒。因此,我们可以找到木盒数最多的方格,再更新相邻方格木盒个数,不断重复这个过程,直到所有方格都满足要求。我们可以使用一个单调队列来维护最大值。每个方格最多会被push进队列4次(4个邻居),这个算法时间复杂度是O(RClog(RC))的。

重要代码示例

for(int i=0;i<r;i++)
	{
		for(int j=0;j<c;j++)q.push({g[i][j],i*r+j});//第一位存储木盒个数,第二位存储id
	}//先将初始个数全部加到队列里
	LL ans=0;
	while(!q.empty())
	{
		auto hh=q.front();
		q.pop();
		int x=q.second/r,y=q.second%r,v=q.first;
		if(c!=g[x][y])continue;//不是最新值,跳过
		for(int i=0;i<4;i++)
		{
			int xx=x+dx[i],yy=y+dy[i];//邻居的坐标
			if(xx<0||xx>=r||yy<0||yy>=r)continue;
			if(g[xx][yy]<g[x][y]-1)//需要更新
			{
				ans+=g[x][y]-1-g[xx][yy];//先更新答案
				g[xx][yy]=g[x][y]-1;
				q.push({g[xx][yy],xx*r+yy});//把新的个数推进队列里
			}
		}
	}

本轮所有题目题解(已完结)

K-Goodness String
L-Shaped Plots
Rabbit House
Checksum

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值