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
因为每个节点要走三遍,搞个三进制。
由于是三进制的状态压缩,相对于二进制的状态压缩较为难处理。
比如 46(1201) 相当于去了1一次 2二次 3零次 4一次
然后解释一下 digit (x,y) 就是x状态 第y位三进制状态值 如上述digit(46,2)=2
然后范围是3^10所以数组开8万就够了
third是用来划分最大状态范围的 如小于third(10)就是状态量小于3^10
dp(x,y)的意思是x状态最后一个走的点是y结尾的最小状态
dp方程为
dp[i+third[k]][k]=min(dp[i][j]+tu[j][k],dp[i+third[k]][k]);
即为本状态加上加上下一次走的状态以k结尾中 (上一状态加上到k的距离 和 之前转移到此状态)的最小值
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<iostream>
#define inf 0x3f3f3f3f
using namespace std;
int digit[80000][11];
int third[12];
int dp[80000][11];
int tu[15][15];
void init()
{
third[0]=1;
for(int i=1;i<=11;i++)
{
third[i]=third[i-1]*3;
}
for(int i=0;i<third[10];i++) //°üº¬ÁË3^10µÄËùÓÐ״̬Êý×Ö
{
int temp=i;
for(int j=0;j<10;j++)
{
digit[i][j]=temp%3;
temp/=3;
}
}
}
int main()
{
int n,m;
init();
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
tu[i][j]=tu[j][i]=inf;
}
}
for(int i=0;i<third[n];i++)
{
for(int j=0;j<n;j++)
dp[i][j]=inf;
}
int u,v,w;
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&u,&v,&w);
tu[u-1][v-1]=tu[v-1][u-1]=min(w,tu[u-1][v-1]);
}
for(int i=0;i<n;i++)
{
dp[third[i]][i]=0;
}
int ans=inf;
for(int i=0;i<third[n];i++)//所有状态枚举一遍
{
bool flag=1;
for(int j=0;j<n;j++)//枚举每个状态的各个位置
{
if(digit[i][j]==0)//如果存在0 说明有的景点没有走过 不可以进行结果计算
{
flag=0;//而且表明的是j结尾的点,下述状态转移无法转移到这个状态,所以无法参与结果计算
}
if(dp[i][j]!=inf)//是由初始结果转移过来的
{
for(int k=0;k<n;k++)//枚举走的位置
{
if(tu[j][k]!=inf&&digit[i][k]!=2)//可以走
{
dp[i+third[k]][k]=min(dp[i][j]+tu[j][k],dp[i+third[k]][k]);
}
}
}
}
if(flag)
for(int s=0;s<n;s++)
ans=min(ans,dp[i][s]);
}
if(ans>=inf)
printf("-1\n");
else
printf("%d\n",ans);
}
}