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
这题真的好坑,竟然有重边,题目也没说,wa了好久,现在终于ac了,新东西是这个是一个三进制的状态量了,和2进制直接操作有点区别
代码
#include<cstdio>
#include<cstring>
#include<algorithm>
#include <iostream>
#include<cmath>
#include <string>
#define mod 9973
#define MAXN 0x1f1f1f1f
using namespace std;
int bit[]={0,1,3,9,27,81,243,729,2187,6561,19683,59049};
int dp[59050][11];
int mapp[11][11];
int num[59050][11];
void init()//一个数字(状态)在各个位上的表示,会了三进制,那4进制以上都差不多
{
int s;
for(int i=0;i<bit[11];i++)
{
s=i;
for(int j=1;j<=10;j++)
{
num[i][j]=s%3;
s/=3;
}
}
}
int main()
{
int n,m;
init();
while(scanf("%d%d",&n,&m)==2)
{
memset(mapp,MAXN,sizeof(mapp));
int x,y,d;
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&x,&y,&d);
if(d<mapp[x][y])//考虑重边
{
mapp[x][y]=d;
mapp[y][x]=d;
}
}
memset(dp,MAXN,sizeof(dp));
for(int i=1;i<=n;i++)
dp[bit[i]][i]=0;
int ans=MAXN;
for(int s=0;s<bit[n+1];s++)
{
bool sign=true;
for(int i=1;i<=n;i++)
{
if(!num[s][i])sign=false;//如果各个为上的状态存在0位,说明这个不是一个可比的状态
if(dp[s][i]==MAXN)
continue;
for(int j=1;j<=n;j++)
{
if(i==j||mapp[i][j]==MAXN||num[s][j]>=2)
continue;
int s1=s+bit[j];
dp[s1][j]=min(dp[s1][j],dp[s][i]+mapp[i][j]);//当前状态对未来某个状态的影响,这个有点像边的松弛操作
}
}
if(sign)
{
for(int i=1;i<=n;i++)
ans=min(ans,dp[s][i]);
}
}
if(ans==MAXN)
printf("-1\n");
else
printf("%d\n",ans);
}
return 0;
}