#include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <set> #include <vector> #include <map> #include <queue> #include <set> #include <algorithm> #include <limits.h> using namespace std; typedef long long LL; const int MAXN=1e+4; const int MAXM=1e+5; const int INF = INT_MAX; struct Edge { int from,to,ci,next; Edge(){} Edge(int _from,int _to,int _ci,int _next):from(_from),to(_to),ci(_ci),next(_next){} }e[MAXM]; int head[MAXN],tot; int dis[MAXN]; int top,sta[MAXN],cur[MAXN]; inline void init(){ memset(head,-1,sizeof(head)); tot=0; } inline void AddEdge(int u,int v,int ci0,int ci1=0){ e[tot]=Edge(u,v,ci0,head[u]); head[u]=tot++; e[tot]=Edge(v,u,ci1,head[v]); head[v]=tot++; } inline bool bfs(int st,int et){ memset(dis,0,sizeof(dis)); dis[st]=1; queue <int> q; q.push(st); while(!q.empty()){ int now=q.front(); q.pop(); for(int i=head[now];i!=-1;i=e[i].next){ int next=e[i].to; if(e[i].ci&&!dis[next]){ dis[next]=dis[now]+1; if(next==et)return true; q.push(next); } } } return false; } LL Dinic(int st,int et){ LL ans=0; while(bfs(st,et)){ top=0; memcpy(cur,head,sizeof(head)); int u=st,i; while(1){ if(u==et){ int pos,minn=INF; for(i=0;i<top;i++) { if(minn>e[sta[i]].ci){ minn=e[sta[i]].ci; pos=i; } } for(i=0;i<top;i++){ e[sta[i]].ci-=minn; e[sta[i]^1].ci+=minn; } top=pos; u=e[sta[top]].from; ans+=minn; } for(i=cur[u];i!=-1;cur[u]=i=e[i].next) if(e[i].ci&&dis[u]+1==dis[e[i].to])break; if(cur[u]!=-1){ sta[top++]=cur[u]; u=e[cur[u]].to; } else { if(top==0)break; dis[u]=0; u=e[sta[--top]].from; } } } return ans; } int t,n,m,d; char map1[30][30]; char map2[30][30]; set <int> s; set <int> ::iterator it; bool check(int x,int y){ if(x-d<1||x+d>n||y-d<1||y+d>m)return true; return false; } int main() { int cas=0; scanf("%d",&t); while(t--){ scanf("%d%d",&n,&d); init(); s.clear(); for(int i=1;i<=n;i++) scanf(" %s",map1[i]+1); for(int i=1;i<=n;i++) scanf(" %s",map2[i]+1); for(int i=1;map1[1][i];i++) m=i; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) { if(check(i,j)&&map1[i][j]!='0') { s.insert(i*m+j); AddEdge(i*m+j,1,map1[i][j]-'0'); } else if(map1[i][j]!='0') { AddEdge(i*m+j,(i+n)*m+j,map1[i][j]-'0'); for(int ii=i-d;ii<=i+d;ii++) for(int jj=j-d;jj<=j+d;jj++) { int dd=(i-ii)*(i-ii)+(j-jj)*(j-jj); if(i==ii&&j==jj)continue; if(dd<=d*d&&map1[ii][jj]!='0'){ AddEdge((i+n)*m+j,ii*m+jj,map1[i][j]-'0'); } } } } LL ans=0; for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) if(map2[i][j]=='L'){ AddEdge(0,i*m+j,1); ++ans; } ans-=Dinic(0,1); printf("Case #%d: ",++cas); if(ans==0)puts("no lizard was left behind."); else if(ans==1)puts("1 lizard was left behind."); else printf("%I64d lizards were left behind.\n",ans); } return 0; }
|