HDU 3001 Travelling 三进制状压DP
2015-07-07 17:51
381 查看
题意:一个图,每个点都要遍历到,且每个点最多经过两次。
思路:用三进制表示状态,第i位上的数(0,1,2)代表第i+1个点经过的次数。
设dp[S][v]为状态S下,到达S状态中的点v的最小花费。
S0 为 状态S中第v-1位的值-1后的结果 ,其他位上的值不变。
那么状态转移方程:dp[S][v] = min(dp[S0][u] + maps[u][v],dp[S][v]).(u在状态S0中)
我的代码:
思路:用三进制表示状态,第i位上的数(0,1,2)代表第i+1个点经过的次数。
设dp[S][v]为状态S下,到达S状态中的点v的最小花费。
S0 为 状态S中第v-1位的值-1后的结果 ,其他位上的值不变。
那么状态转移方程:dp[S][v] = min(dp[S0][u] + maps[u][v],dp[S][v]).(u在状态S0中)
我的代码:
#include<cstdio> #include<cstring> #include<iostream> #define min(a,b) (a < b ? a : b) using namespace std; typedef int LL; const LL inf = 0x3f3f3f3f; const LL maxn = 11; LL n,m; LL maps[maxn][maxn]; LL dp[177147][11]; LL mod_pow(LL n){ LL res = 1,a = 3; while(n){ if(n & 1) res *= a; a *= a; n >>= 1; } return res; } void init(){ for(int i=0;i<=n;i++){ for(int j=0;j<=n;j++){ if(i == 0 || j == 0 || i == j) maps[i][j] = 0; else maps[i][j] = inf; } } } bool check(LL S){ LL tmp; for(LL i = 0;i < n; i++){ tmp = mod_pow(i); if((S / tmp) % 3 == 0) return false; } return true; } void solve(){ LL S,S0,v,u,tmp; LL Ed = mod_pow(n); for(S = 0;S < Ed; S++){ for(v = 1; v <= n; v++){ dp[S][v] = inf; tmp = mod_pow(v - 1); if((S / tmp) % 3 == 0) continue; S0 = S - tmp; if(S0 == 0) dp[S][v] = 0; else{ for(u = 1;u <= n; u++){ tmp = mod_pow(u - 1); if(v == u || (S0 / tmp) % 3 == 0) continue; dp[S][v] = min(dp[S][v],dp[S0][u] + maps[u][v]); } } } } LL res = inf; for(S = 0;S < Ed; S++){ if(check(S)){ for(v = 1; v <= n ; v++) res = min(res,dp[S][v]); } } if(res == inf) printf("-1\n"); else printf("%d\n",res); } int main(){ while(~scanf("%d%d",&n,&m)){ init(); LL a,b,c; while(m--){ scanf("%d%d%d",&a,&b,&c); maps[a][b] = maps[b][a] = min(maps[a][b],c); } solve(); } return 0; }
相关文章推荐
- LeetCode131:Palindrome Partitioning
- C#.NET 大型企业信息化系统集成快速开发平台 4.2 版本 - 防止脱库、防止篡改数据
- [leedcode 20] Valid Parentheses
- 显著性检测(Saliency Detection)
- Predicate和Consumer接口– Java 8中java.util.function包下的接口
- 阿里面试题目总结
- Eigen与Matlab语法及语义辞典
- JAVA字符串的GZIP压缩解压缩方法
- Spinner简单使用
- 设备
- STA分析(一)
- python with用法
- C#读取Excel数据动态生成对象并进行序列化
- 4.4从图库选择图片,获取图片路径并裁剪
- Matlab移植到Eigen用到的词条
- android Tabhost部件(一)
- java编程思想-——static关键字
- 亚马逊开源它的 TLS 库-s2n,
- 【大数据分析】 浅析大数据及企业策略
- Html中tr th 和 tr td的区别