历届试题 剪格子
时间限制:1.0s 内存限制:256.0MB
问题描述
如下图所示,3 x 3 的格子中填写了一些整数。
+--*--+--+
|10* 1|52|
+--****--+
|20|30* 1|
*******--+
| 1| 2| 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
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
1 1 1 1
1 30 80 2
1 1 1 100
样例输出2
10
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <set>
#include <queue>
using namespace std;
#define maxn 105
#define inf 0x7ffffff
typedef long long ll;
pair <int ,int > p;
int arr[maxn][maxn];
int dir[4][2] ={0,1,0,-1,-1,0,1,0};
int vis[maxn][maxn];
int n,m;
int sum = 0;
int ans;
void dfs(int s,int t,int tmpx,int tmpy);
bool check(int x,int y);
int main()
{
scanf("%d%d",&n,&m);
sum = 0;
ans = inf;
memset(vis,0,sizeof(vis));
for(int i = 0; i < m; i++){
for(int j = 0;j < n; j++){
scanf("%d",&arr[i][j]);
sum += arr[i][j];
}
}
if(sum % 2 == 1){
printf("0\n");
return 0;
}
sum /= 2;
vis[0][0] = 1;
dfs(arr[0][0],1,0,0);
if(ans >= inf){
printf("0\n");
}else{
printf("%d\n",ans);
}
return 0;
}
void dfs(int s,int t,int tmpx,int tmpy){
if(s > sum){
return ;
}
if(s == sum){
if(t < ans){
ans = t;
}
return ;
}
for(int i = 0; i < 4; i++){
int x = tmpx+dir[i][0];
int y = tmpy+dir[i][1];
if(check(x,y)){
vis[x][y] = 1;
dfs(s+arr[x][y],t+1,x,y);
vis[x][y] = 0;
}
}
}
bool check(int x,int y){
if(x < 0 || x >= m || y < 0 || y >= n || vis[x][y]){
return false;
}
return true;
}