记录
代码:
#include<bits/stdc++.h>
#define maxn 505
#define reg register
#define int long long
#define inf 0x3f3f3f3f
using namespace std;
int n,m,k,w,lim,cnt,root=-1;
struct an_edge
{
int to,w,nxt;
}ls[maxn*2];
int head[maxn],f[1<<11][maxn],vis[maxn],a[maxn];
int ans[maxn];
pair<int,int> pre[1<<11][maxn];
inline void add(int fr,int to,int w)
{
ls[++cnt]=(an_edge){to,w,head[fr]};
head[fr]=cnt;
}
void dfs(int u,int s)
{
if(!pre[s][u].second)return;
ans[u]=1;
if(pre[s][u].first==u)dfs(u,s ^ pre[s][u].second);
dfs(pre[s][u].first, pre[s][u].second);
}
inline void add_spot(int x,int y)
{
cin>>w;
int now=(x-1)*m+y-1;a[now]=w;
if(w==0)
{
f[1<<k][now]=0;k++;
root=root==-1?now:root;
}
if(x>1)add(now-m,now,w);
if(x<n)add(now+m,now,w);
if(y>1)add(now-1,now,w);
if(y<m)add(now+1,now,w);
}
void SPFA(int s)//coc is the Chapion of Cyrodill
{
queue<int >q;
for(reg int i=1;i<=n*m;i++)if(f[s][i]<inf){q.push(i);vis[i]=1;}//if we can start here
while(!q.empty())
{
int u=q.front();q.pop();vis[u]=0;
for(reg int i=head[u];i;i=ls[i].nxt)
{
int v=ls[i].to,w=ls[i].w;
if(f[s][u]+w<f[s][v])
{
f[s][v]=f[s][u]+w;
if(!vis[v]){q.push(v);vis[v]=1;}
pre[s][v]=make_pair(u,s);
}
}
}
}
signed main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);cout.tie(0);
memset(f,0x3f,sizeof f);
cin>>n>>m;
for(reg int i=1;i<=n;i++)for(reg int j=1;j<=m;j++)add_spot(i,j);
lim=1<<k;
for(reg int c=0;c<lim;c++)
{
for(reg int i=c&(c-1);i;i=(i-1)&c)
{
if(i<(i^c))break;
for(reg int z=0;z<n*m;z++)if(f[c][z]>f[i][z]+f[c^i][z])
{
f[c][z]=f[i][z]+f[c^i][z];
pre[c][z]=make_pair(z,i);
}
}
SPFA(c);
}
cout<<f[lim-1][root]<<endl;
dfs(root,lim-1);
for(reg int i=1,tot=0;i<=n;i++)
{
for(reg int j=1;j<=n;j++)
{
if(!a[tot])cout<<'x';
else cout<<(ans[tot] ? 'o' : '_');
tot++;
}
cout<<endl;
}
return 0;
}