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
题意:N个点,M个边,一个人可以以这N个点任意一点为起点,问在每个点访问2次以下的情况下访问所有的点的最小值
分析:TSP问题,3进制的状态压缩
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <queue>
#define mem(p,k) memset(p,k,sizeof(p));
#define rep(a,b,c) for(int a=b;a<c;a++)
#define pb push_back
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
int n,m,minn;
int mapp[15][15],dp[100000][15],_3[15],bit[100000][15];
int main()
{
_3[0]=1;
for(int i=1;i<=10;i++)_3[i]=3*_3[i-1];
for(int i=0;i<_3[10];i++){
int num=i,cur=0;
while(num){
bit[i][cur++]=num%3;
num/=3;
}
}
while(~scanf("%d%d",&n,&m)){
mem(mapp,inf);
mem(dp,inf);
for(int i=0;i<m;i++){
int x,y,l;
scanf("%d%d%d",&x,&y,&l);
x--;y--;
mapp[x][y]=mapp[y][x]=min(mapp[x][y],l);
}
for(int i=0;i<n;i++){
dp[_3[i]][i]=0;
}
int cur;
minn=inf;
for(int i=0;i<_3[n];i++){
cur=1;
for(int j=0;j<n;j++){
if(bit[i][j]==0)cur=0;
if(dp[i][j]==inf)continue;
for(int k=0;k<n;k++){
if(j==k || mapp[j][k]==inf || bit[i][k]>=2)continue;
dp[i+_3[k]][k]=min(dp[i+_3[k]][k],dp[i][j]+mapp[j][k]);
}
}
if(cur){
for(int k=0;k<n;k++)
minn=min(minn,dp[i][k]);
}
}
if(minn!=inf)cout<<minn<<endl;
else cout<<-1<<endl;
}
return 0;
}