uva 167 - The Sultan's Successors
来源:互联网 发布:windows系统平板电脑 编辑:程序博客网 时间:2024/05/18 00:07
点击打开链接
题目意思:给定8 x 8的一个方格,对于该方格来说每一行上面只能取一个数,然后同行同列同对角线上都是不满足,求出所能得到的最大值
解题思路:8皇后的变形问题,变为求解所有方案数中的最大的和。我们先分序一下,该解空间的结构,由于每一行只能取一,那么我么就可以知道每一行对应的是解空间的一层,那么我么就可以去搜索这个解空间状态树,从第一行开始搜索,如果行数大于8就return,比较最大的值,在搜索函数里面我们用一个for循环枚举每一列,求出满足条件的一列,通过judge函数去判断,只要判断上面和左边和对角线满足即可,因为后面还不知道,这样就能够遍历整个解空间。
代码:
#include <iostream>#include <cstdio>#include <cstring>#include <cstdlib>#include <list>#include <vector>#include <stack>#include <algorithm>using namespace std;const int MAXN = 9;int k, ans;int val[MAXN][MAXN];int vis[MAXN][MAXN];//判断函数int judge(int x, int y) { int i, j; //上方向 for (i = x - 1; i >= 1; i--) { if (vis[i][y]) return 0; } //左方向 for (i = y - 1; i >= 1; i--) { if (vis[x][i]) return 0; } //对角线 for (i = 1; i <= 8; i++) { for (j = 1; j <= 8; j++) { if (abs(i - x) == abs(j - y)) {//判断对角线的条件 if (vis[i][j]) return 0; } } } return 1;}//深搜回溯求解void dfs(int i , int max) { if(i > 8){//如果大于8那么直接更新最大值然后return if (max > ans) ans = max; return; } for(int j = 1 ; j <= 8 ; j++){//这一行遍历过去找到满足的点 if (vis[i][j] == 0 && judge(i, j)) { vis[i][j] = 1; dfs(i + 1 , max + val[i][j]);//递归到下一行 vis[i][j] = 0;//状态的回溯 } }}//主函数int main() { int i, j; scanf("%d", &k); while (k--) { memset(val, 0, sizeof (val)); memset(vis, 0, sizeof (vis)); for (i = 1; i <= 8; i++) { for (j = 1; j <= 8; j++) scanf("%d", &val[i][j]); } ans = 0; dfs(1 , 0); printf("%5d\n", ans); }}
- UVa 167 - The Sultan's Successors
- Uva 167 The Sultan's Successors
- uva 167 - The Sultan's Successors
- uva 167 - The Sultan's Successors
- UVa 167 - The Sultan's Successors
- Uva-167-The Sultan's Successors
- uva 167 - The Sultan's Successors
- UVa 167 - The Sultan's Successors
- uva 167 - The Sultan's Successors
- uva 167 The Sultan's Successors
- uva 167 The Sultan's Successors
- UVa 167 - The Sultan's Successors
- UVa 167 - The Sultan's Successors
- UVa 167 - The Sultan's Successors
- UVA 167 - The Sultan's Successors
- UVA - 167 The Sultan's Successors
- UVA - 167 The Sultan's Successors
- uva 167 The Sultan's Successors 搜索
- 使用javascript用一种非主流的方式提交POST表单
- android控制view的大小和位置(二)
- C/C++程序中执行shell命令的2种方法
- 轻松掌握AJAX(Jquery)异步通信
- poj 1692 求数字匹配对数
- uva 167 - The Sultan's Successors
- 界面测试用例的设计方法
- csdn题目(含解答)
- vim下区块的复制与黏贴
- java读写xml文件的方法
- 个人认为最佳模板制作方案
- Printf()输出格式控制
- 常量指针 和 指针常量
- 指向多维数组的指针变量