这道题目最多只有10个点,问每个点最多去两次,存不存在一种方案,花费最少并且可以每一个点都去过至少一次。这显然是一道状态压缩的DP问题,因为是最多去两次,那么我们用三进制保存每一种状态。
刚开始脑残了,以为最终答案在11111或者2222中,wa了很多次。另外注意题目中有重边出现,要注意判重。
状态转移方程 dp[s][i]=min(dp[s][i],dp[s'][k]+dis[k][i]) ; dp[s][i] 表示在编号为s的状态下,最后到i的情况下最小的花费。 s‘=s-begin[i] ,begin[i]数组保存三进制每一位的权。
Travelling
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 2030 Accepted Submission(s): 579
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
Sample Output
100 90 7#include<iostream> #include<cstring> #include<string> #include<cstdio> using namespace std; #define INF 0x3FFFFFF #define min(a,b) (a<b?a:b) int n,m; int maps[11][11]; int dp[59500][11],s[59500][11]; int begin[]={0,1,3,9,27,81,243,729,2187,6561,19683,59049}; void init() //初始化所有状态 { for(int i=0;i<59050;i++) { int k=i; for(int j=1;j<=10;j++) { s[i][j]=k%3; k/=3; if(!k) break; } } } void solve() { int a,b,c,tmps; for(int i=0;i<=n;i++) for(int j=0;j<=n;j++) maps[i][j]=INF; for(int i=0;i<m;i++) { scanf("%d%d%d",&a,&b,&c); if(c<maps[a][b]) maps[b][a]=maps[a][b]=c; } for(int i=0;i<begin[n+1];i++) for(int j=0;j<=n;j++) dp[i][j]=INF; for(int i=0;i<=n;i++) dp[begin[i]][i]=0; int ans=INF; for(int i=0;i<begin[n+1];i++) { int all=1; //此标记非常重要啊。。。 for(int j=1;j<=n;j++) { if(!s[i][j]) { all=0; continue; } for(int k=1;k<=n;k++) { if(i==j) continue; if(maps[k][j]==INF) continue; if(s[i][k]==0) continue; tmps=i-begin[j]; if(dp[tmps][k]==INF) continue; dp[i][j]=min(dp[i][j],dp[tmps][k]+maps[k][j]); } } if(all) { for(int j=1;j<=n;j++) ans=min(ans,dp[i][j]); } } if(ans==INF) { printf("-1\n"); return; } printf("%d\n",ans); } int main() { init(); while( ~scanf("%d%d",&n,&m)) solve(); return 0; }