[POJ 3311]Hie with the Pie——再谈TSP问题的DP解法
来源:互联网 发布:iapp源码文件夹 编辑:程序博客网 时间:2024/05/21 11:09
题目连接:
http://poj.org/problem?id=3311
题目大意:有n+1个点,给出点0~n的每两个点之间的距离,求这个图上TSP问题的最小解
思路:用二进制数来表示访问过的城市集合,f[{S}][j]=已经访问过的城市集合为S,访问了j个城市,所需的最少花费。
这里提一下二进制数表示集合的方法(这里不妨设集合中最多有n个元素):
如果集合S中最多会出现n个元素,则用长度为n的二进制数来表示集合S,每一位代表一个元素,该位为0表示该元素在集合S中不存在,为1表示该元素在集合S中存在
位数 4 3 2 1
S 1 0 1 1
这个集合S里有元素1、2、4
下面是二进制数表示几种集合运算的方法
1、集合S的全集U=(1<<n)-1
2、检查集合S中是否含元素i S&(1<<(i-1)) (返回0表示不存在,返回1表示存在)
3、从集合S中去除元素i S^(1<<(i-1))
下面是本题的思路:
首先对整个图跑一次Floyd多源最短路,得到两两点之间的最短距离,然后用DP求解,f[{S}][j]=已经访问过的城市集合为S,访问了j个城市,所需的最少花费。f[S][i]=min{f[S-{j}][j]+dist[j][i]}
最后得到的答案ans=min(f[全集][i]+dist[i][0])
代码:
#include <iostream>#include <stdio.h>#include <string.h>#include <stdlib.h>#include <algorithm>#define MAXN 15#define MAXM 1<<15#define INF 0x3f3f3f3fusing namespace std;int f[MAXM][MAXN]; //f[{S}][j]=已经访问过的城市集合为S,访问了j个城市,所需的最少花费int dist[MAXN][MAXN]; //点与点之间的距离int n;int min(int a,int b){ if(a<b) return a; return b;}void Floyd(){ for(int k=0;k<=n;k++) for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j]);}int TSP() //DP求TSP{ memset(f,0x7f,sizeof(f)); for(int s=0;s<(1<<n);s++) //枚举访问城市集合S,全集为(1<<n)-1 for(int i=1;i<=n;i++) //枚举最近访问过的城市i if(s&(1<<(i-1))) //city(i)∈S { if(s==(1<<(i-1))) //{city(i)}==S f[s][i]=dist[0][i]; else { for(int j=1;j<=n;j++) //枚举上一次访问的城市j if((s&(1<<(j-1)))&&i!=j) //城市j不和i相同 f[s][i]=min(f[s][i],f[s^(1<<(i-1))][j]+dist[j][i]); //Cs {city(J)}=s^(1<<(i-1)) } } int ans=INF; for(int i=1;i<=n;i++) ans=min(ans,f[(1<<n)-1][i]+dist[i][0]); return ans;}int main(){ while(scanf("%d",&n)&&n) { memset(dist,0,sizeof(dist)); for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) scanf("%d",&dist[i][j]); Floyd(); printf("%d\n",TSP()); } return 0;}
0 0
- [POJ 3311]Hie with the Pie——再谈TSP问题的DP解法
- POJ 3311 Hie with the Pie (TSP问题 状压DP解法)
- 【DP】 POJ 3311 Hie with the Pie 状压 TSP问题
- POJ 3311 Hie with the Pie(TSP问题DP解)
- POJ 3311--Hie with the Pie(状压dp+TSP)
- POJ 3311 Hie with the Pie -- TSP 状态压缩dp
- POJ 3311-Hie with the Pie(floyd+TSP 状压DP)
- POJ 3311 Hie with the Pie - 状压dp【TSP】
- poj 3311 Hie with the Pie(TSP ,状压dp)
- HDU 3311 Hie with the Pie(状压dp+TSP问题)
- poj 3311 Hie with the Pie (TSP)
- poj 3311 Hie with the Pie (TSP问题)
- POJ 3311 Hie with the Pie TSP问题 -
- POJ 3311 Hie with the Pie(经典TSP问题)
- POJ 3311 Hie with the Pie(经典TSP问题)
- POJ 3311 Hie with the Pie (Floyd + 状压dp 简单TSP问题)
- POJ 3311 Hie with the Pie(TSP问题 状压DP)
- POJ 3311 Hie with the Pie (状态压缩DP ,tsp问题)
- android adb常用命令
- time_t和struct tm之间的转换
- STL之set与hash_set
- C++ 中的比较函数
- C++ Mysql的数据库连接池的实现
- [POJ 3311]Hie with the Pie——再谈TSP问题的DP解法
- hive从查询中获取数据插入到表或动态分区
- 二叉树非递归遍历
- 链表的实现(Java语言描述)
- python解决osx安装PIL时的_imagingft.c:73:10: fatal error: 'freetype/fterrors.h' file not found
- android_radioplay
- mysql链接用户添加
- ACM排序算法sort()与qsort()用法
- 远程桌面调试tricks