7-12 Rabbit (300 分)

As we all know, rabbits like to jump, and Rabbit Xuan is no exception.

Rabbit Xuan have a very big house, which can be seen as an n×m 2D grid. There are several boxes on each grid, and the height of each box is one meter, so Rabbit Xuan can jump happily on it.

But now you realize that because Rabbit Xuan is too small, if she jumps more than 1 meter, she may be in danger. In order to protect Rabbit Xuan, you are going to reform the house. For each adjacent grid, you want the height difference between them to be no more than 1 meter. Two grids are considered adjacent if they share a common side.

You can’t remove the boxes because they were glued in the beginning. But you can add boxes at will, so you want to ensure the safety of Rabbit Xuan with the least boxes.

Input:
The first line of the input gives the number of test cases, T. T test cases follow.

Each test case begins with a line containing two integers n and m.

Then, n lines follow, each with m integers. The j-th integer on i-th line,represents how many boxes are there initially on the cell located at the i-th row and j-th column of the grid.

Output:
For each test case, output one line containing the minimum number of boxes to be added so that the rabbit’s house is safe.

Sample input:
3
1 3
3 4 3
1 3
3 0 0
3 3
0 0 0
0 2 0
0 0 0
Sample output:
0
3
4
Hint:
1≤T≤3

1≤n,m≤300

#include<bits\stdc++.h>
using namespace std;
vector<pair<int, int>> heaps[2000005];
int D[4][2] = { {-1,0},{0,1},{1,0},{0,-1} };
int main() {
	int T;
	cin >> T;
	int n, m;
	for (int k = 0; k < T; k++) {
		cin >> n >> m;
		for (int i = 0; i <= 2000000; ++i) heaps[i].clear();
		vector<vector<int>> G(n+1, vector<int>(m+1, 0));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				cin >> G[i][j];
				heaps[G[i][j]].push_back(make_pair(i, j));
			}
		}
		long long int ans = 0;
		for (int now = 2000000; now >= 0; now--) {
			for (int item = 0; item < heaps[now].size(); item++) {
				int x = heaps[now][item].first;
				int y = heaps[now][item].second;
				for (int c = 0; c < 4; c++) {
					int tx = x + D[c][0], ty = y + D[c][1];
					if (0 <= tx&&tx < n && 0 <= ty&&ty < m&&G[tx][ty]<now - 1) {
						ans += now - 1 - G[tx][ty];
						G[tx][ty] = now - 1;
						heaps[G[tx][ty]].push_back(make_pair(tx, ty));
					}
				}

			}
	   }
		cout << ans << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值