题解: Nuts
pdf 题面好评
题意
八连通的网格图,问从起点出发经过每个坚果并回到起点的最短路。
算法
一眼旅行商问题,求出任意两个坚果间的距离(由于是八连通图,所以是 Chebyshev 距离),然后跑状压 DP 即可。
令
为什么直接这样做是对的,不会重复经过坚果?因为可以斜着走,可以绕过来时的路而距离不变。
程序
#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define uint unsigned int
#define ull unsigned long long
#define lll __int128
#define db double
#define ld long double
#define fi first
#define se second
#define endl '\n'
#define ainl inline __attribute__((always_inline))
#define inf 0x3f3f3f3f
#define ninf 0xcfcfcfcf
#define infll 0x3f3f3f3f3f3f3f3f
#define ninfll 0xcfcfcfcfcfcfcfcf
#define start_mtest\
int tcnt;\
cin>>tcnt;\
for(int tcase=1;tcase<=tcnt;tcase++)\
{
#define end_test goto end_of_test
#define end_mtest\
end_of_test:;\
}
#define N 100010
int r,c,n,ans;
pair<int,int>A[20];
int G[20][20],DP[(1<<16)+10][20];
ainl int dis(pair<int,int>x,pair<int,int>y)
{
return max(abs(x.fi-y.fi),abs(x.se-y.se));
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
while(cin>>r>>c)
{
n=1;
for(int i=1;i<=r;i++)
for(int j=1;j<=c;j++)
{
char ch;
cin>>ch;
if(ch=='#')A[++n]={i,j};
else if(ch=='L')A[1]={i,j};
}
if(n==1)
{
cout<<0<<endl;
continue;
}
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
G[i][j]=dis(A[i],A[j]);
memset(DP,0x3f,sizeof(DP));
DP[1][1]=0;
for(int i=1;i<=(1<<n)-1;i++)
for(int j=2;j<=n;j++)
if(i&(1<<j-1))
for(int k=1;k<=n;k++)
if(k!=j&&i&1<<k-1)
DP[i][j]=min(DP[i][j],DP[i^(1<<j-1)][k]+G[k][j]);
ans=inf;
for(int i=2;i<=n;i++)
ans=min(ans,DP[(1<<n)-1][i]+G[i][1]);
cout<<ans<<endl;
}
return 0;
}