把题目转化成图的形式,然后就是个经典的TSP。
[code]:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#define th(x) this->x=x
using namespace std;
const int inf = 0x3f3f3f3f;
struct Node{
int x,y;
void init(int x,int y){
th(x);th(y);
}
}o,ps[25];
int n,m,tot;
char s[21][21];
int dp[1<<16][16];
int dist(Node a,Node b){
int d1 = max(abs(a.x-b.x),abs(a.y-b.y));
//d2 = max(abs(a.x-b.x),abs(a.y-b.y));
return d1;
}
void init(){
tot = 0;
}
int sol(){
int i,j,S,Ed,S_,ans = inf;
Ed = 1<<tot;
for(S = 1;S < Ed;S++)for(i = 0;i < tot;i++) dp[S][i] = inf;
for(S = 1;S < Ed;S++){
for(i=0;i<tot;i++){
if(!(S>>i&1)) continue;
S_ = S^(1<<i);
if(!S_){
dp[S][i] = dist(o,ps[i]);
continue;
}
for(j = 0;j < tot;j++){
if(!(S_>>j&1)) continue;
dp[S][i] = min(dp[S][i],dp[S_][j]+dist(ps[i],ps[j]));
}
}
}
for(i = 0;i < tot;i++) ans = min(ans,dp[Ed-1][i]+dist(ps[i],o));
return ans;
}
int main(){
int i,j,cas,T;
scanf("%d",&cas);
for(T = 1;T <= cas;T++){
scanf("%d%d",&n,&m);
init();
for(i = 0;i < n;i++) scanf("%s",s[i]);
for(i = 0;i < n;i++){
for(j = 0;j < m;j++){
if(s[i][j]=='g') ps[tot++].init(i,j);
else if(s[i][j]=='x') o.init(i,j);
}
}
if(tot)
printf("Case %d: %d\n",T,sol());
else printf("Case %d: 0\n",T);
}
return 0;
}