[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;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人