hdu 3001 Travelling (TSP 三进制,状压dp)

来源:互联网 发布:印度 伊朗 知乎 编辑:程序博客网 时间:2024/06/02 05:30
After coding so many days,Mr Acmer wants to have a good rest.So travelling is the best choice!He has decided to visit n cities(he insists on seeing all the cities!And he does not mind which city being his start station because superman can bring him to any city at first but only once.), and of course there are m roads here,following a fee as usual.But Mr Acmer gets bored so easily that he doesn't want to visit a city more than twice!And he is so mean that he wants to minimize the total fee!He is lazy you see.So he turns to you for help.
Input
There are several test cases,the first line is two intergers n(1<=n<=10) and m,which means he needs to visit n cities and there are m roads he can choose,then m lines follow,each line will include three intergers a,b and c(1<=a,b<=n),means there is a road between a and b and the cost is of course c.Input to the End Of File.
Output
Output the minimum fee that he should pay,or -1 if he can't find such a route.
Sample Input
2 11 2 1003 21 2 402 3 503 31 2 31 3 42 3 10
Sample Output
100907 
题意:还是TSP ,不过这里是每个城市可以去两次,而且是他的起点可以是任意位置。
思路:首先一个城市可以去两次,那也就是说每个城市的状态有 0,1,2三种,我们可以很容易的想到利用三进制,接下来是 任意位置,那就是构造出dp[state][i]=0;其中state表示的是 只有第i位为1其他都是0的三进制数。接下来上代码吧
#include<stdio.h>#include<string.h>#include<algorithm>#define inf  0x3f3f3f3fusing namespace std;int n,m,dist[11][11];int three[11],dp[60000][11],allthree[60000][12];void init()//构造出 只有第i位是1其他位是0的三进制数 {three[0]=1;for(int i=1;i<=11;i++){three[i]=three[i-1]*3;}}int main(){init();while(scanf("%d%d",&n,&m)!=EOF){memset(dist,-1,sizeof(dist));int a,b,c,ans=inf;for(int i=0;i<m;i++){scanf("%d%d%d",&a,&b,&c);//记得判重边 a--,b--;if(dist[a][b]==-1)dist[b][a]=dist[a][b]=c;else dist[a][b]=dist[b][a]=min(dist[a][b],c);}for(int i=0;i<three[n];i++)//打表得出所有三进制数 {int te=i;for(int j=0;j<10;j++){allthree[i][j]=te%3;te=te/3;}}memset(dp,inf,sizeof(dp));for(int i=0;i<n;i++)//任意起点 {dp[three[i]][i]=0;}for(int state=0;state<three[n];state++){int flag=1;for(int i=0;i<n;i++){if(allthree[state][i]==0) flag=0;if(dp[state][i]==inf) continue;for(int k=0;k<n;k++){if(allthree[state][k]>=2|| dist[i][k]==-1||i==k) continue;int next=state+three[k];//这里应该比较不好理解 就是我们在第k位变成1 那么我们就是原状态加上第k位是1其他位是0的三进制数就好了 //printf("next=%d\n",next);dp[next][k]=min(dp[next][k],dp[state][i]+dist[i][k]); }}if(flag==1)// 这里flag等于一是说当你把所有的点全部遍历完之后再比较大小 {for(int j=0;j<n;j++){ans=min(ans,dp[state][j]);}}}if(ans==inf) puts("-1");else printf("%d\n",ans);}}


原创粉丝点击