HDU - 3001 Travelling(三进制状压dp)
Travelling
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.
InputThere 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.OutputOutput the minimum fee that he should pay,or -1 if he can't find such a route.Sample Input
2 1 1 2 100 3 2 1 2 40 2 3 50 3 3 1 2 3 1 3 4 2 3 10
Sample Output
100 90 7
题意:每个点最多去两次,给出边权,求从任意一点开始经过所有点的最短路。
经典TSP问题,只不过最多一次的条件变为两次,这里可以用三进制思想解决。
three[n]表示n个地点的全部状态,0没去过,1去过一次,2去过两次,dig[i][j]记录在i状态下第j位的数字(0-2)。
#include<bits/stdc++.h> #define MAX 12 #define INF 0x3f3f3f3f using namespace std; typedef long long ll; int a[MAX][MAX]; int three[MAX]; int dig[60000][MAX]; int dp[60000][MAX]; void init(){ three[0]=1; for(int i=1;i<=10;i++){ three[i]=three[i-1]*3; } for(int i=0;i<three[10];i++){ int ii=i,c=-1; while(ii){ c++; dig[i][c]=ii%3; ii/=3; } } } int main() { int t,n,m,i,j,k; int x,y,z; init(); while(~scanf("%d%d",&n,&m)){ memset(a,INF,sizeof(a)); for(i=0;i<m;i++){ scanf("%d%d%d",&x,&y,&z); a[x][y]=a[y][x]=min(a[x][y],z); } memset(dp,INF,sizeof(dp)); for(i=0;i<n;i++){ dp[three[i]][i]=0; } for(i=0;i<three[n];i++){ for(j=0;j<n;j++){ if(dig[i][j]==0) continue; for(k=0;k<n;k++){ if(j==k||dig[i][k]==0) continue; dp[i][j]=min(dp[i][j],dp[i-three[j]][k]+a[k+1][j+1]); } } } int ans=INF; for(i=0;i<three[n];i++){ int f=0; for(j=0;j<n;j++){ if(dig[i][j]==0){ f=1; break; } } if(f==1) continue; for(j=0;j<n;j++){ ans=min(ans,dp[i][j]); } } if(ans==INF) printf("-1\n"); else printf("%d\n",ans); } return 0; }
博文系博主原创,转载请注明出处 o(* ̄▽ ̄*)ブ 更多博文源自https://www.cnblogs.com/yzm10
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步