其他分享
首页 > 其他分享> > 91. 最短Hamilton路径

91. 最短Hamilton路径

作者:互联网

题目链接

91. 最短Hamilton路径

给定一张 \(n\) 个点的带权无向图,点从 \(0∼n−1\) 标号,求起点 \(0\) 到终点 \(n−1\) 的最短 Hamilton 路径。

Hamilton 路径的定义是从 \(0\) 到 \(n−1\) 不重不漏地经过每个点恰好一次。

输入格式

第一行输入整数 \(n\)。

接下来 \(n\) 行每行 \(n\) 个整数,其中第 \(i\) 行第 \(j\) 个整数表示点 \(i\) 到 \(j\) 的距离(记为 \(a[i,j]\))。

对于任意的 \(x,y,z\),数据保证 \(a[x,x]=0,a[x,y]=a[y,x]\) 并且 \(a[x,y]+a[y,z]≥a[x,z]\)。

输出格式

输出一个整数,表示最短 Hamilton 路径的长度。

数据范围

\(1≤n≤20\)
\(0≤a[i,j]≤10^7\)

输入样例:

5
0 2 4 5 1
2 0 6 5 3
4 6 0 8 3
5 5 8 0 5
1 3 3 5 0

输出样例:

18

解题思路

状压dp

分析:状态为 \(i\) 且处于 \(j\) 点说明 \(i\) 的二进制下 \(j\) 位为 \(1\) 且由 \(k\) 转移到 \(j\) 说明 \(i\bigoplus (1<<j)\) 的 \(k\) 为 \(1\)

代码

// Problem: 最短Hamilton路径
// Contest: AcWing
// URL: https://www.acwing.com/problem/content/93/
// Memory Limit: 256 MB
// Time Limit: 5000 ms
// 
// Powered by CP Editor (https://cpeditor.org)

// %%%Skyqwq
#include <bits/stdc++.h>
 
//#define int long long
#define help {cin.tie(NULL); cout.tie(NULL);}
#define pb push_back
#define fi first
#define se second
#define mkp make_pair
using namespace std;
 
typedef long long LL;
typedef pair<int, int> PII;
typedef pair<LL, LL> PLL;
 
template <typename T> bool chkMax(T &x, T y) { return (y > x) ? x = y, 1 : 0; }
template <typename T> bool chkMin(T &x, T y) { return (y < x) ? x = y, 1 : 0; }
 
template <typename T> void inline read(T &x) {
    int f = 1; x = 0; char s = getchar();
    while (s < '0' || s > '9') { if (s == '-') f = -1; s = getchar(); }
    while (s <= '9' && s >= '0') x = x * 10 + (s ^ 48), s = getchar();
    x *= f;
}

const int N=1<<20;
int a[25][25],n,f[N][25];
int main()
{
    cin>>n;
    for(int i=0;i<n;i++)
    	for(int j=0;j<n;j++)cin>>a[i][j];
    memset(f,0x3f,sizeof f);
    f[1][0]=0;
    for(int i=1;i<1<<n;i++)
    	for(int j=0;j<n;j++)
    		if(i>>j&1)
    			for(int k=0;k<n;k++)
    				if((i^(1<<j)>>k)&1)f[i][j]=min(f[i][j],f[i^(1<<j)][k]+a[k][j]);
    cout<<f[(1<<n)-1][n-1];
    return 0;
}

标签:int,路径,long,最短,Hamilton,91,define
来源: https://www.cnblogs.com/zyyun/p/15947220.html