0
点赞
收藏
分享

微信扫一扫

poj 2078(搜索+剪枝)

花明 2023-05-29 阅读 48



解题思路:可以一行一行地递归求解,要是不符合条件就回溯,注意最后一行不能够移动它,因为可能会与之前重叠。。






#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;
}





举报

相关推荐

0 条评论