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个城市都玩一遍,但同一个城市不想玩超过两次,告诉你这m条道路的花费,然后这个人可以任选一个城市作为起点出发,问你将这n个城市玩一遍的最少花费为多少,如果不能则输出-1
思路:因为同一个城市不能经过超过两次,所以我们可以用三进制来压缩状态,表示去过的次数。
代码如下
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
using namespace std;
#define ll long long
const int INF=0x3f3f3f3f;
int n,m;
int dp[15][60005];
int mp[15][15];
int thre[20];
void init()
{
thre[0]=1;
for(int i=1;i<=10;i++)
thre[i]=thre[i-1]*3;
}
int solve(int wei[],int state)//求出状态state下已经到达过的城市的数量
{
int sum=0;
for(int i=0;i<n;i++)
{
wei[i]=state%3;
state/=3;
if(wei[i])
sum++;
}
return sum;
}
int main ()
{
init();
while(cin>>n>>m)
{
memset(dp,INF,sizeof(dp));
memset(mp,-1,sizeof(mp));
while(m--)
{
int x,y,c;
cin>>x>>y>>c;
x--;
y--;
if(mp[x][y]==-1)
{
mp[x][y]=mp[y][x]=c;
}
else
{
mp[x][y]=mp[y][x]=min(mp[x][y],c);
}
}
int ans=INF;
for(int state=1;state<thre[n];state++)//枚举状态state
{
int wei[12];
int num=solve(wei,state);
for(int i=0;i<n;i++)//枚举此时所在城市
if(wei[i])
{
if(num==1)
dp[i][state]=0;
if(dp[i][state]==-1)
continue;
if(num==n)//已经将所有城市玩过
{
ans=min(ans,dp[i][state]);
}
for(int j=0;j<n;j++)//枚举下一个去的城市
if(i!=j&&wei[j]<2&&mp[i][j]!=-1)
{
int nex=state+thre[j];
dp[j][nex]=min(dp[j][nex],dp[i][state]+mp[i][j]);
}
}
}
if(ans==INF)
cout<<-1<<endl;
else
cout<<ans<<endl;
}
return 0;
}