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
思路: 3进制进行压缩,0 1 2 代表经过这个点的次数,每次利用一个点更新它可以到达的状态,具体实现在代码中
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define eps 1e-8
typedef __int64 ll;
#define fre(i,a,b) for(i = a; i <b; i++)
#define mem(t, v) memset ((t) , v, sizeof(t))
#define sf(n) scanf("%d", &n)
#define sff(a,b) scanf("%d %d", &a, &b)
#define sfff(a,b,c) scanf("%d %d %d", &a, &b, &c)
#define pf printf
#define bug pf("Hi\n")
using namespace std;
#define INF 0x3f3f3f3f
#define N 12
int type[N]={0,1,3,9,27,81,243,729,2187,6561,19683,59049};
int dp[59050][12]; //dp[i][j] i 状态下终点为j的情况
int dig[59050][12]; //dig[i][j] i 状态下第j位走过的次数
int dis[N][N]; // i~j的距离
int n,m;
void inint()
{
int i,j,t;
fre(i,0,59050)
{
int t=i;
fre(j,1,12)
{
dig[i][j]=t%3;
t/=3;
if(!t) break;
}
}
}
int main()
{
int i,j;
inint();
while(~sff(n,m))
{
mem(dis,INF);
mem(dp,INF);
int s,e,len;
while(m--)
{
sfff(s,e,len);
if(dis[s][e]>len) dis[s][e]=dis[e][s]=len;
}
fre(i,1,n+1)
dp[type[i]][i]=0;
len=type[n+1];
int cur;
int ans=INF;
bool all_vis;
fre(cur,0,len)
{
all_vis=true; //判断 cur 状态 是不是所有点都走过
fre(i,1,n+1)
{
if(dig[cur][i]==0) //根据i更新别的点,如果i没有到达,那么continue;
{
all_vis=false;
continue;
}
if(dp[cur][i]==INF) continue;
fre(j,1,n+1)
{
if(i==j) continue;
if(dig[cur][j]>=2||dis[i][j]==INF) continue;
//j已经被走2便了
int to=cur+type[j];
dp[to][j]=min(dp[to][j],dp[cur][i]+dis[i][j]);
}
}
if(all_vis)
fre(j,1,n+1)
ans=min(ans,dp[cur][j]);
}
if(ans==INF) ans=-1;
pf("%d\n",ans);
}
return 0;
}