题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3001
Travelling
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11880 Accepted Submission(s): 3736
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
题意:给出一个图,问经过所有点的最小边权和,每个点最多经过两次。如果无法找到一条路径,则输出-1.
解题思路,设dp【i】【j】为经过j状态时,且最后到达i点的最小权值和。状态j为三进制下,每个数位代表经过每个点的次数。
#include<bits/stdc++.h> #define inf 0x3f3f3f3f using namespace std; typedef long long ll; int dp[15][200000]; int mp[15][15]; int bit[15]; int pos[15]; int main(){ int n,m; bit[0]=1; for(int i=1;i<15;i++){ bit[i]=bit[i-1]*3; } while(scanf("%d%d",&n,&m)!=EOF){ memset(mp,0x3f,sizeof(mp)); memset(dp,0x3f,sizeof(dp)); int a,b,c; for(int i=0;i<m;i++){ scanf("%d%d%d",&a,&b,&c); mp[a-1][b-1]=mp[b-1][a-1]=min(mp[a-1][b-1],c); } for(int i=0;i<n;i++){ dp[i][bit[i]]=0; } for(int i=1;i<bit[n];i++){ int tem=i; for(int j=0;j<n;j++){ pos[j]=tem%3; tem/=3; } for(int j=0;j<n;j++){ if(pos[j]!=0){ for(int k=0;k<n;k++){ if(k!=j&&pos[k]<2){ dp[k][i+bit[k]]=min(dp[k][i+bit[k]],dp[j][i]+mp[j][k]); } } } } } int ans=inf; for(int i=0;i<n;i++){ for(int j=1;j<bit[n];j++){ int flag=1; int tem=j; for(int k=0;k<n;k++){ if(tem%3==0){ flag=0; break; } tem/=3; } if(flag)ans=min(dp[i][j],ans); } } if(ans==inf)puts("-1"); else printf("%d\n",ans); } // printf("%d\n",bit[11]-1); return 0; }
原文地址:https://www.cnblogs.com/Zhi-71/p/11440659.html