解题思路:可以一行一行地递归求解,要是不符合条件就回溯,注意最后一行不能够移动它,因为可能会与之前重叠。。
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 8;
int n,mat[maxn][maxn],ans;
int get_max(int dep)
{
int m = 0, sum = 0;
for(int i = 1; i <= n; i++){
sum = 0;
for(int j = 1; j <= dep; j++){
sum += mat[j][i];
}
m = max(m,sum);
}
return m;
}
void dfs(int dep)
{
int tmp,m;
if(dep == n){
m = get_max(dep);
if(m < ans) ans = m;
return;
}
for(int i = 1; i <= n; i++){
tmp = mat[dep][1];
for(int j = 2; j <= n; j++){
swap(tmp,mat[dep][j]);
}
swap(tmp,mat[dep][1]);
m = get_max(dep);
if(m > ans) continue;
dfs(dep+1);
}
}
int main()
{
while(scanf("%d",&n),n != -1){
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
scanf("%d",&mat[i][j]);
ans = get_max(n);
dfs(1);
printf("%d\n",ans);
}
return 0;
}
标签:剪枝,int,一行,dep,2078,poj,ans,maxn,include From: https://blog.51cto.com/u_16143128/6373669