算法提高 金陵十三钗 状压DP
来源:互联网 发布:excel数据套打 编辑:程序博客网 时间:2024/04/29 09:43
思路:深度搜索复杂度N!过不了。考虑动态规划:将已经选择的列记为1,未选择表示0,二进制压缩,例如110,就表示选择了第1列和第2列。
d(i, t)表示当前已经匹配了i行,选择了t这些列。状态转移:
for(int i = 0; i < n; ++i) {int x = 1 << i;if(x & val) d = max(d, like[row][i] + dfs(row+1, val - x, k-1));}
此时总的状态数就是1<<n,相比N!是极大的优化,减少了很多重复情况的搜索。
用记忆化搜索,代码很好写。
#include <cstdio>#include <cmath>#include <algorithm>#include <cstring>#include <utility>#include <string>#include <iostream>#include <map>#include <set>#include <vector>#include <queue>#include <stack>using namespace std;#pragma comment(linker, "/STACK:1024000000,1024000000") #define eps 1e-10#define inf 0x3f3f3f3f#define PI pair<int, int> typedef long long LL;const int maxn = 13 + 5;int like[maxn][maxn], dp[maxn][1<<13];int n, ans;int dfs(int row, int val, int k) { //row表示行,k表示当前选择了多少列 if(dp[row][val] != -1) return dp[row][val];int &d = dp[row][val];if(k == 1) { //边界 for(int i = 0; i < n; ++i) {int x = 1 << i;if(x & val) return d = like[row][i];}}for(int i = 0; i < n; ++i) {int x = 1 << i;if(x & val) d = max(d, like[row][i] + dfs(row+1, val - x, k-1));}return d;}int main() {while(scanf("%d", &n) == 1) {for(int i = 0; i < n; ++i) for(int j = 0; j < n; ++j) {scanf("%d", &like[i][j]);}memset(dp, -1, sizeof(dp));int start = (1<<n)-1;printf("%d\n", dfs(0, start, n));}return 0;}
如有不当之处欢迎指出!
0 0
- 算法提高 金陵十三钗 状压DP
- 算法提高 金陵十三钗
- 算法提高 金陵十三钗 状态亚索DP
- 蓝桥杯算法提高 -- 金陵十三钗
- 蓝桥杯 算法提高 金陵十三钗
- 蓝桥杯 算法提高 金陵十三钗
- 蓝桥杯_算法提高_金陵十三钗(简单枚举)
- 蓝桥杯_算法提高_金陵十三钗(动态规划)
- 蓝桥杯 金陵十三钗
- 《金陵十三钗》后感
- mj评《金陵十三钗》-9分
- 金陵十二钗
- 金陵十二钗
- 算法提高 拿糖果 DP
- 算法提高 求最大值 DP
- 金陵十三衩中想到的国民党德式师
- 算法提高 金属采集 树形DP
- 算法提高 拿糖果 线性DP
- Eclipse的Servers中无法添加Tomcat6/7
- yii2.0 我要和你做朋友
- 【计算机网络】TCP报文首部中URG和PSH
- delphi 关键字总结
- spark性能调优与BUG修正
- 算法提高 金陵十三钗 状压DP
- JVM内存结构
- 谷歌云平台自身如何使用Kubernetes?
- iOS开发之展示gif图像
- 写一个简单的Spring MVC
- Unity3D 大型游戏 最后一站 源码 部分重点ResourceManager(2)
- Oracle-ORA-00923: 未找到要求的FROM关键字-Oracle不支持TOP N查询
- 【LeetCode题解】21.Merge Two Sorted Lists
- JAVA集合常见比较(hashmap/hashtable/concurrenthashtable、hashset/treeset/linkedhashset)