TravellingTime Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 7394 Accepted Submission(s): 2405
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
Source
Recommend
gaojie
|
題意:
一個人需要在n個城市間找出起點且一個城市至多可以經過兩次,求出必須經過所有城市的最小花費。如果無解則輸出"-1"。
思路:
n很小可以利用三進制來存下每個城市經過次數的狀態。dp數組第一維就是狀態,第二維目前該人所在城市的編號,具體細節看代碼吧。
狀態轉移方程:dp[i+val[u]][v]=min(dp[i][u]+map[u][v],dp[i+val[u]][v])
這裏的val[u]表示城市i被壓縮狀態後的數值,i是未從u走到v的狀態,dp[i][u]就是未走的花費,那麼i+val[u]就是已從u走到v的狀態,dp[i][u]+map[u][v]就是已走的花費,用它去更新dp[i+val[u]][v]即可。
示例程序
Problem : 3001 ( Travelling ) Judge Status : Accepted
RunId : 20826751 Language : GCC Code Len : 1549 B
Code Render Status : Rendered By HDOJ GCC Code Render Version 0.01 Beta
#include <stdio.h>
#include <string.h>
#define MAX 0x3f3f3f3f
int dp[59050][10],map[10][10],val[11]={1,3,9,27,81,243,729,2187,6561,19683,59049};
int min(int x,int y)
{
if(x<y)
{
return x;
}
else
{
return y;
}
}
int main()
{
int n,m,i,i1,i2,ans,u,v,w,flag;
while(scanf("%d %d",&n,&m)!=EOF)
{
memset(dp,MAX,sizeof(dp));
memset(map,MAX,sizeof(map));
ans=MAX;
for(i=1;m>=i;i++)
{
scanf("%d %d %d",&u,&v,&w);
u--;
v--;
map[u][v]=min(map[u][v],w); //防止重邊
map[v][u]=map[u][v];
}
for(i=0;n>i;i++) //對於每個城市都只經過一次,等同於我們對每個城市設置起點
{
dp[val[i]][i]=0;
}
for(i=1;val[n]>i;i++) //枚舉各個城市經過多少次的狀態
{
flag=1;
for(i1=0;n>i1;i1++) //相當於從一個城市到另一個城市的出發點
{
if(i/val[i1]%3==0) //存在有城市一次都沒經過
{
flag=0;
continue;
}
for(i2=0;n>i2;i2++) //相當於從一個城市到另一個城市的目的地
{
if(i/val[i2]%3!=2) //當前城市已經經過2次不可再走
{
dp[i+val[i2]][i2]=min(dp[i][i1]+map[i1][i2],dp[i+val[i2]][i2]); //狀態轉移方程
}
}
}
if(flag==1) //如果有沒經過的城市,肯定不能更新答案
{
for(i1=0;n>i1;i1++)
{
ans=min(ans,dp[i][i1]);
}
}
}
if(ans==MAX)
{
ans=-1;
}
printf("%d\n",ans);
}
return 0;
}