[HDU3001] Travelling 解题报告(三进制状压dp,TSP)
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.
InputThere 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.
OutputOutput 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 10Sample Output
100 90 7
这道题很明显的是TSP(旅行商问题),但是注意题目:每个城市可以走两次;那么我们要怎么记录它的状态呢?当时的想法是用三进制压缩,后来为了方便用四进制,一个进制直接浪费掉,节约时间降低编码难度。后来还是用了三进制,因为四进制用的内存过大,还是用回了三进制
因为S状态下,城市的排列可能有多种,那么我们用最后一个城市来区分不同的状态
dp[S][j]是在状态为S时,结尾为j城市的状态
pow3是关于3的各幂的预处理
S-pow3[i]表示删去第i个元素
压缩之后
直接遍历所有的S
然后遍历所有输入S的j,以j为结尾,找到删去j后所有状态并依此推出j的最优状态;
那么代码如下
#include <iostream>
#include <cstring>
using namespace std;
int dp[60000][11];
int graph[11][11];
int pow3[11]={1,3,9,27,81,243,729,2187,6561,19683,59049};
bool check(int n,int a)
{
while(n--)
{
if(a%3==0) return false;
a/=3;
}
return true;
}
int main()
{
int n,m;
while(cin>>n>>m)
{
memset(dp,0x3F,sizeof(dp));
for(int i=0;i<n;i++)
{
dp[pow3[i]][i]=0;
}
memset(graph,0x3F,sizeof(graph));
for(int i=0;i<m;i++)
{
int a,b,c;
cin>>a>>b>>c;
a--;b--;
graph[a][b]=graph[b][a]=min(graph[a][b],c);
}
for(int i=0;i<pow3[n];i++)
{
for(int j=0;j<n;j++)
{
if(i/pow3[j]%3!=0)
for(int k=0;k<n;k++)
{
if(k==j) continue;
if(i/pow3[k]%3==0) continue;
dp[i][j]=min(dp[i][j],dp[i-pow3[j]][k]+graph[j][k]);
}
}
}
int ans=0x3F3F3F3F;
for(int i=0;i<pow3[n];i++)
{
for(int j=0;j<n;j++)
{
if(check(n,i))
{
ans=min(ans,dp[i][j]);
}
}
}
if(ans==0x3F3F3F3F)
cout<<-1<<endl;
else
cout<<ans<<endl;
}
return 0;
}