首页 > 代码库 > HDU 3001 Travelling(DP状态压缩)
HDU 3001 Travelling(DP状态压缩)
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题意:每个城市游览次数d>=1&&d<=2问最小花费。三进制状态转移:dp[status+num[j]][j]=min(dp[status+num[j]][j],dp[status][i]+dis[i][j]);#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<limits.h> typedef long long LL; using namespace std; #define REPF( i , a , b ) for ( int i = a ; i <= b ; ++ i ) #define REP( i , n ) for ( int i = 0 ; i < n ; ++ i ) #define CLEAR( a , x ) memset ( a , x , sizeof a ) const int INF=0x3f3f3f; int dp[60000][11];//记录i状态下以j为终点的值 int f[60000][11];//记录i状态下j点的访问次数 int num[12]; int dis[15][15]; int n,m; void init() { num[1]=1; REPF(i,2,11) num[i]=num[i-1]*3; for(int i=0;i<num[11];i++) { int temp=i; REPF(j,1,10) { f[i][j]=temp%3; temp/=3; } } // for(int i=1;i<=10;i++) // cout<<"2333 "<<f[12][i]<<endl; } int main() { int x,y,val; init(); while(~scanf("%d%d",&n,&m)) { CLEAR(dp,INF); CLEAR(dis,INF); // cout<<"23333 "<<INF<<endl; while(m--) { scanf("%d%d%d",&x,&y,&val); if(dis[x][y]>val) dis[x][y]=dis[y][x]=val; } REPF(i,1,n) dp[num[i]][i]=0; // cout<<"2333 "<<dp[3][2]<<" "<<dp[2][3]<<endl; int ans=INF; for(int status=1;status<num[n+1];status++) { int ok=1; REPF(i,1,n) { if(f[status][i]==0)//在状态status下的i次数为0,ok=0,还有地方没有游 ok=0; if(dp[status][i]==INF)//不存在这条道路 continue; REPF(j,1,n) { if(i==j) continue; if(f[status][j]==2) continue;//状态status下j点走过两次 if(dis[i][j]==INF) continue; dp[status+num[j]][j]=min(dp[status+num[j]][j],dp[status][i]+dis[i][j]);//状态转移 } } if(ok) { REPF(i,1,n) ans=min(ans,dp[status][i]); } } if(ans==INF) ans=-1; printf("%d\n",ans); } return 0; }
HDU 3001 Travelling(DP状态压缩)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。