hdu3001

来源:互联网 发布:avr单片机 编辑:程序博客网 时间:2024/06/15 18:12

Travelling

Time Limit: 6000/3000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 8036    Accepted Submission(s): 2621


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 11 2 1003 21 2 402 3 503 31 2 31 3 42 3 10
 

Sample Output
10090

7

三进制状态压缩DP

#include"cstdio"#include"cstring"#include"iostream"#include"algorithm"using namespace std;const int INF = 0x3f3f3f3f;const int maxn = 2e5+5;int n,m;int dp[maxn][15];int mp[15][15];int dig[15];int sta[maxn][15];void init(){    dig[0] = 1;    for(int i = 1; i <= 10; i++){        dig[i] = dig[i-1]*3;    }    for(int i = 0; i < dig[10]; i++){        int x = i;        for(int j = 0; j < 10; j++){            sta[i][j] = x%3;            x /= 3;        }    }}int main(){    init();    while(~scanf("%d%d",&n,&m)){        memset(mp,INF,sizeof(mp));        for(int i = 1; i <= m; i++){            int u,v,cost;            scanf("%d%d%d",&u,&v,&cost);            --u;    --v;            mp[u][v] = mp[v][u] = min(mp[u][v],cost);        }        memset(dp,INF,sizeof(dp));        for(int i = 0; i < n; i++)            dp[dig[i]][i] = 0;        for(int s = 0; s < dig[n]; s++){            for(int j = 0; j < n; j++){                if(dp[s][j] == INF) continue;                for(int k = 0; k < n; k++){                    if(sta[s][k] >= 2) continue;                    dp[s+dig[k]][k] = min(dp[s+dig[k]][k], dp[s][j] + mp[j][k]);                }            }        }        int ans = INF;        for(int s = 0; s < dig[n]; s++){            bool flag = 1;            for(int j = 0; j < n; j++){                if(!sta[s][j]){                    flag = 0;                    break;                }            }            if(flag){                for(int j = 0; j < n; j++){                    ans = min(ans,dp[s][j]);                }            }        }        if(ans < INF) printf("%d\n",ans);        else puts("-1");    }    return 0;}

原创粉丝点击