标签:bsp namespace sam cin 题目 TE 问题 int #define
4
0 2 1 3
2 0 2 1
1 2 0 1
3 1 1 0
4
从0到3的Hamilton路径有两条,0-1-2-3和0-2-1-3。前者的长度为2+2+1=5,后者的长度为1+2+1=4
经典状态压缩DP,可惜我太菜,写了接近三个小时。
注意他要终点必须是n-1。
#include <bits/stdc++.h>
#define maxn 20
using namespace std;
typedef long long ll;
const int maxv=1<<20;
int mps[maxn][maxn]={0};
int dp[maxv+5][maxn];
const int inf=1e9;
int main()
{
int n,i,j,k;
cin>>n;
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
cin>>mps[i][j];
}
}
int sum=(1<<n)-1;
//cout<<sum<<endl;
for(i=2;i<sum;i++)
{
//if(!(i&1)) continue;
for(j=0;j<n;j++)
{
int temp=1<<j;
if(i&temp)
{
if(i==temp)
{
dp[i][j]=mps[0][j];
}
else
{ dp[i][j]=inf;
for(k=0;k<n;k++)
{
if(i&(1<<k)&&j!=k)
{
dp[i][j]=min(dp[i][j],dp[i-temp][k]+mps[k][j]);
}
}
}
}
}
}
dp[sum][n-1]=inf;
for(i=0;i<n-1;i++)
{
int temp=1<<(n-1);
dp[sum][n-1]=min(dp[sum-temp][i]+mps[i][n-1],dp[sum][n-1]);
}
cout<<dp[sum][n-1]<<endl;
return 0;
}
标签:bsp namespace sam cin 题目 TE 问题 int #define
原文地址:https://www.cnblogs.com/zyf3855923/p/9216786.html