蓝桥杯历届试题剪格子解题报告---搜索 & 回溯

版权声明:转载请注明出处:https://blog.csdn.net/qq1013459920 https://blog.csdn.net/qq1013459920/article/details/88074448

                                                历届试题 剪格子

问题描述

如下图所示,3 x 3 的格子中填写了一些整数。

+--*--+--+
|10* 1|52|
+--****--+
|20|30* 1|
*******--+
| 1| 2| 3|
+--+--+--+

我们沿着图中的星号线剪开,得到两个部分,每个部分的数字和都是60。

本题的要求就是请你编程判定:对给定的m x n 的格子中的整数,是否可以分割为两个部分,使得这两个区域的数字和相等。

如果存在多种解答,请输出包含左上角格子的那个区域包含的格子的最小数目。

如果无法分割,则输出 0。

输入格式

程序先读入两个整数 m n 用空格分割 (m,n<10)。

表示表格的宽度和高度。

接下来是n行,每行m个正整数,用空格分开。每个整数不大于10000。

输出格式

输出一个整数,表示在所有解中,包含左上角的分割区可能包含的最小的格子数目。

样例输入1

3 3
10 1 52
20 30 1
1 2 3

样例输出1

3

样例输入2

4 3
1 1 1 1
1 30 80 2
1 1 1 100

样例输出2

10

搜索题,注意一下细节还是很容易的。

getVal()函数计算数组a[]所取路径上的和

可以提前判断是否可以分割:

如果所有格子数值和为奇数,则肯定无法分割,直接输出0

dfs函数深搜所有路径,一旦路径和 = 所有格子数值和的一半,则进行判断,取最少格子数

AC Code:

#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <climits>
using namespace std;
typedef long long ll;
#define lowbit(x) x & -x;
#define INF 0x3f3f3f3f;
const static int MAX_N = 1e6 + 5;
const static int dir[4][2] = { {1, 0}, {-1, 0}, {0, 1}, {0, -1} };
int n, m;
int sum, res;
int maps[15][15];
bool vis[15][15];
int a[105];
bool inbound(int x, int y) {
	return (x >= 0 && x < n && y >= 0 && y < m);
}
int getVal(int s, int e) {//获取路径和
	int ret = 0;
	for (int i = s; i <= e; i++) {
		ret += a[i];
	}
	return ret;
}
void dfs(int x, int y, int s) {
	/*for (int i = 0; i < s; i++) {
		printf("%d ", a[i]);
	}
	putchar('\n');*/
	if (sum == getVal(0, s - 1)) {	//出口:路径和为格子总值的一半
		res = min(res, s);
	}
	for (int k = 0; k < 4; k++) {
		int fx = x + dir[k][0];
		int fy = y + dir[k][1];
		if (inbound(fx, fy) && !vis[fx][fy]) {
			a[s] = maps[fx][fy];
			vis[fx][fy] = true;
			dfs(fx, fy, s + 1);
			vis[fx][fy] = false;
		}
	}
}
int main() {
	while (scanf("%d%d", &m, &n) != EOF) {
		sum = 0;
		res = INF;
		memset(vis, false, sizeof(vis));
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				scanf("%d", &maps[i][j]);
				sum += maps[i][j];
			}
		}
		if (sum & 1) {
			printf("0\n");
			continue;
		}
		sum >>= 1;
		a[0] = maps[0][0];	//必须包含左上角格子
		vis[0][0] = true;
		dfs(0, 0, 1);
		if (res < INT_MAX) {	
			printf("%d\n", res);
		}
		else {
			//路径上无法找到分割一半的方案(数据不强,这里不写也可以过)
			printf("0\n");
			continue;
		}
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq1013459920/article/details/88074448
今日推荐