Travelling 三进制压缩,算出每一种状态的最优值
Problem Description
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 1
1 2 100
3 2
1 2 40
2 3 50
3 3
1 2 3
1 3 4
2 3 10
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
90
7
***************************************************************************************************************************
&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 /* 2 三进制压缩,因为有0,1,2三种状态,算出每种状态时的花费, 3 最终算出最优值。 4 */ 5 #include<iostream> 6 #include<string> 7 #include<cstring> 8 #include<cstdio> 9 using namespace std; 10 const int INF=0x3f3f3f3f; 11 int s[12],dp[60000][12],tir[60000][12],map[12][12],n,m,i,j,k; 12 void init() 13 { 14 s[0]=1; 15 int it,jt; 16 for(it=1;it<=10;it++) 17 s[it]=s[it-1]*3; 18 for(it=0;it<=s[10];it++) 19 { 20 int tmp=it; 21 for(jt=0;jt<10;jt++) 22 { 23 tir[it][jt]=tmp%3; 24 tmp/=3; 25 } 26 } 27 } 28 void DP() 29 { 30 int it,jt,kt,ans=INF; 31 for(it=0;it<s[n];it++) 32 { 33 int flag=1; 34 for(jt=0;jt<n;jt++) 35 { 36 if(tir[it][jt]==0)flag=0;//表示jt城市未遍历到 37 if(dp[it][jt]==INF) 38 continue; 39 for(kt=0;kt<n;kt++) 40 { 41 if(jt==kt||tir[it][kt]==2)continue; 42 if(map[jt][kt]==INF)continue; 43 int ls=it+s[kt]; 44 dp[ls][kt]=min(dp[ls][kt],dp[it][jt]+map[jt][kt]); 45 } 46 } 47 if(flag) 48 { 49 for(jt=0;jt<n;jt++) 50 ans=min(ans,dp[it][jt]); 51 } 52 } 53 if(ans==INF) 54 printf("-1\n"); 55 else 56 printf("%d\n",ans); 57 } 58 int main() 59 { 60 init(); 61 int a,b,c; 62 while(~scanf("%d %d",&n,&m)) 63 { 64 memset(dp,INF,sizeof(dp)); 65 memset(map,INF,sizeof(map)); 66 for(i=0;i<n;i++)dp[s[i]][i]=0; 67 while(m--) 68 { 69 scanf("%d%d%d",&a,&b,&c); 70 a--;b--; 71 map[a][b]=map[b][a]=min(map[a][b],c); 72 } 73 DP(); 74 } 75 }