# BZOJ 2595 [Wc2008]游览计划（斯坦纳树）

$dp[s][i][j]=min(dp[s][i][j],dp[k][i][j]+dp[s$^$k][i][j]-val(i,j))\ (k\subset s)$
$dp[s][i][j]=min(dp[s][i][j],min(dp[s][i+1][j],dp[s][i-1][j],dp[s][i][j+1],dp[s][i][j-1])+val(i,j))$

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
using namespace std;
const int N=15;
const int INF=1e9;
int xx[]={0,0,0,1,-1};
int yy[]={0,1,-1,0,0};
struct node{
int x,y,w;
node(int xx=0,int yy=0,int ww=0){
x=xx;y=yy;w=ww;
}
};
struct from{
int a,b,c;
from(int aa=0,int bb=0,int cc=0){
a=aa,b=bb,c=cc;
}
}pre[1111][N][N];
bool operator <(node a,node b){
return a.w>b.w;
}
priority_queue<node> q;
bool vis[N][N];
int n,m,a[N][N],t,dp[1111][N][N];
void dij(int k){
memset(vis,0,sizeof(vis));
while(!q.empty()){
node u=q.top();q.pop();
int x=u.x,y=u.y;
if(vis[x][y])continue;
vis[x][y]=1;
for(int i=1;i<=4;i++){
int X=x+xx[i],Y=y+yy[i];
if(X<1||X>n||Y<1||Y>m)continue;
if(dp[k][X][Y]>dp[k][x][y]+a[X][Y]){
dp[k][X][Y]=dp[k][x][y]+a[X][Y];
pre[k][X][Y]=from(k,x,y);
q.push(node(X,Y,dp[k][X][Y]));
}
}
}
}
int sum=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){sum=sum*10+ch-'0';ch=getchar();}
return sum*f;
}
void dfs(int a,int b,int c){
vis[b][c]=1;
int A=pre[a][b][c].a;
int B=pre[a][b][c].b;
int C=pre[a][b][c].c;
if(A+B+C==0)return;
if(A!=a)dfs(A,b,c),dfs(a^A,b,c);
else dfs(a,B,C);
}
int main(){
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
if(a[i][j]==0)t++;
}
for(int k=0;k<(1<<t);k++)
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
dp[k][i][j]=INF;
t=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(a[i][j]==0)dp[(1<<t++)][i][j]=0;
for(int k=1;k<(1<<t);k++){
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
for(int w=k;w;w=(w-1)&k)
if(dp[k][i][j]>dp[k^w][i][j]+dp[w][i][j]-a[i][j]){
dp[k][i][j]=dp[k^w][i][j]+dp[w][i][j]-a[i][j];
pre[k][i][j]=from(w,i,j);
}
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(dp[k][i][j]!=INF)q.push(node(i,j,dp[k][i][j]));
dij(k);
}
int ans=INF,ida,idb,idc;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
if(ans>dp[(1<<t)-1][i][j]){
ans=dp[(1<<t)-1][i][j];
ida=(1<<t)-1,idb=i,idc=j;
}
printf("%d\n",ans);
memset(vis,0,sizeof(vis));
dfs(ida,idb,idc);
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++)
if(a[i][j]==0)cout<<'x';
else if(vis[i][j])cout<<'o';
else cout<<'_';
printf("\n");
}
return 0;
}

posted @ 2019-02-26 14:03  Xu-daxia  阅读(133)  评论(0编辑  收藏  举报