POJ-2078(dfs + 剪枝)
来源:互联网 发布:洮南幼儿带网络监控的 编辑:程序博客网 时间:2024/06/02 17:41
题目:http://poj.org/problem?id=2078
暴搜加剪枝:rotate实际上是相对的,所以第一行可以不动,而且当发现一行的和不小于当前结果时,可以立马结束本次搜索,另外,取模运算真的很慢呀。。。
#include <cstdio>#include <algorithm>using namespace std;#define INF999999999int n, matrix[7][7];int offset[7], ans;void check(){int maxsum = -INF;for(int j = 0; j < n; ++j){int sum = 0;for(int i = 0; i < n; ++i){int k = j + offset[i];sum += matrix[i][k < n ? k : k - n];}if(sum >= ans) return;maxsum = max(maxsum, sum);}ans = maxsum;}void dfs(int i){if(i == n){check();return;}int& shift = offset[i];for(shift = 0; shift < n; ++shift) dfs(i + 1);}int main(){while(scanf("%d", &n), n != -1){for(int i = 0; i < n; ++i)for(int j = 0; j < n; ++j)scanf("%d", matrix[i] + j);ans = INF;dfs(1);printf("%d\n", ans);}return 0;}
如果手动模拟递归的话,又可以优化一些:
#include <cstdio>#include <cstring>#include <algorithm>using namespace std;#define INF999999999int n, matrix[7][7];int offset[7], ans;void check(){int maxsum = -INF;for(int j = 0; j < n; ++j){int sum = 0;for(int i = 0; i < n; ++i){int k = j + offset[i];sum += matrix[i][k < n ? k : k - n];}if(sum >= ans) return;maxsum = max(maxsum, sum);}ans = maxsum;}int main(){int i, j;while(scanf("%d", &n), n != -1){for(i = 0; i < n; ++i)for(j = 0; j < n; ++j)scanf("%d", matrix[i] + j);if(n == 1){printf("%d\n", matrix[0][0]);continue;}ans = INF;memset(offset, 0, n << 2);while(!offset[0]){for(i = 0; i < n; ++i){offset[n-1] = i;check();}for(j = n-2; j > -1 && ++offset[j] == n; --j) offset[j] = 0;}printf("%d\n", ans);}return 0;}
0 0
- POJ-2078(dfs + 剪枝)
- poj 1011 sticks (dfs+剪枝)
- poj 3900 The Robbery (dfs+剪枝)
- poj 1190 生日蛋糕(DFS+剪枝)
- POJ 3009 Curling 2.0 (dfs剪枝)
- POJ 1724 ROADS(DFS剪枝)
- poj 1190 dfs+剪枝(生日蛋糕)
- POJ - 1011 - Sticks (DFS + 剪枝)
- poj 1011 Sticks (DFS+剪枝)
- POJ 2531 dfs回溯(小剪枝)
- POJ 2531 Network Saboteur(DFS+剪枝)
- POJ 2676 Sudoku (DFS回溯剪枝)
- POJ 1190 生日蛋糕 (dfs + 神剪枝)
- POJ 1011 Sticks (DFS + 剪枝)
- POJ 1011 Sticks(DFS + 剪枝)
- poj 2362 Square(dfs, 剪枝)
- POJ 1011 Sticks(dfs+剪枝)
- POJ 2676Sudoku(Dfs+搜索剪枝)
- Android-overridePendingTransition+Fragment
- SkipList跳表
- 顺序线性表的c++实现
- 有这样一个三位数,在其后面补上三个数字,使之变成一个六位数,这个六位数减去原来的三位数······
- 命令行执行java程序
- POJ-2078(dfs + 剪枝)
- Vim快捷键操作
- poj 2250/3356 LCS(文章LCS/AGTC)
- 指针与数组
- 体验父爱之旅 深悟人生真谛
- 20150317第一天
- 《烦恼都是自找的》之生命的净化器
- 黑马程序员——【OC】面向对象的三大特性
- file.seek(),file.split(),file,sorted(),file.pop用法