Travelling
Time Limit: 6000/3000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 11033 Accepted Submission(s): 3484
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(n<=10)个点,m条无向带权边,问你从任意一点出发遍历所有的点(每个点的经过次数不超过两次)的最短路径长度。
思路:
经典的TSP问题,由于每个点可以经过最多两次,我们使用三进制状态压缩dp,表示当前状态下某个点经过了多少次。
这个题没卡内存,可以预处理每个状态下第i为是01还是2。
代码:
#include<iostream>
#include<cstring>
#include<queue>
#include<cstdio>
#include<cmath>
#include<algorithm>
#define inf 0x3f3f3f3f
#define ll long long
using namespace std;
const int maxn=12;
ll a[maxn][maxn],c[maxn];
ll b[]={0,1,3,9,27,81,243,729,2187,6561,19683,59049};
ll dp[60000][maxn];
ll num[60000][maxn];
int n,m,k;
ll tmp,ans;
ll cal(ll c[])
{
ll sum=0;
for(int i=0;i<n;i++)
sum+=c[i]*b[i];
return sum;
}
void init()
{
for(int i=0;i<59050;i++)
{
int t=i;
for(int j=1;j<=10;j++)
{
num[i][j]=t%3;
t/=3;
if(!t) break;
}
}
}
int main()
{
init();
int T,cas=1;
//scanf("%d",&T);
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=0;i<=n;i++)
for(int j=0;j<=n;j++) a[i][j]=inf;
for(int i=0;i<m;i++)
{
int x,y;
ll z;
scanf("%d%d%lld",&x,&y,&z);
a[x][y]=a[y][x]=min(a[x][y],z);
}
for(int i=0;i<59050;i++)
for(int j=0;j<=n;j++)
dp[i][j]=inf;
for(int i=1;i<=n;i++)
dp[b[i]][i]=0;
ll ans=inf;
for(int i=1;i<b[n+1];i++)
{
int fg=1;
for(int j=1;j<=n;j++)
{
if(num[i][j]==0) fg=0;
if(dp[i][j]==inf) continue;
for(int k=1;k<=n;k++)
{
if(a[j][k]==inf||j==k) continue;
if(num[i][k]==2) continue;
dp[i+b[k]][k]=min(dp[i+b[k]][k],dp[i][j]+a[j][k]);
}
}
if(fg)
for(int j=1;j<=n;j++)
ans=min(ans,dp[i][j]);
}
if(ans!=inf) printf("%lld\n",ans);
else puts("-1");
}
return 0;
}
/*
2 1
1 2 100
3 2
1 2 40
2 3 50
3 3
1 2 3
1 3 4
2 3 10
*/