题意:给你一个网格,网格上的一些位置上有一只蜥蜴,所有蜥蜴的最大跳跃距离是d,如果一只蜥蜴能跳出网格边缘,那么它就安全了.且每个网格有一个最大跳出次数x,即最多有x只蜥蜴从这个网格跳出,这个网格就再也不能有蜥蜴进来了.问你最少有多少只蜥蜴跳不出网格.
思路:和POJ3498差不多...关键是能看懂题目..看题目看的心累..
建图:
源点编号0,网格的每个格子拆成两个点i和i+n*m(n和m为网格的行和列数,其实i编号点是表示蜥蜴进来,而i+n*m编号的点是表示蜥蜴出去).汇点t编号n*m*2+1.
如果格子i上有蜥蜴,那么从s到i有边(s,i,1).
如果格子i能承受x次跳出,那么有边(i,i+n*m,x)
如果从格子i能直接跳出网格边界,那么有边(i+n*m,t,INF)
如果从格子i不能直接跳出网格,那么从i到离i距离<=d的网格j有边(i+n*m,j,INF). 注意这里的距离是abs(行号之差)+abs(列号之差)
最终我们求出的最大流就是能跳出网格的蜥蜴数.
#include <cstdio>
#include <queue>
#include <cstring>
#include <iostream>
#include <cstdlib>
#include <algorithm>
#include <vector>
#include <map>
#include <string>
#include <set>
#include <ctime>
#include <cmath>
#include <cctype>
using namespace std;
#define maxn 1200
#define INF 1<<29
#define LL long long
int cas=1,T;
struct Edge
{
int from,to,cap,flow;
Edge(int u,int v,int c,int f):from(u),to(v),cap(c),flow(f){}
};
int n,m;
struct Dinic
{
// int n,m;
int s,t;
vector<Edge>edges; //边数的两倍
vector<int> G[maxn]; //邻接表,G[i][j]表示结点i的第j条边在e数组中的序号
bool vis[maxn]; //BFS使用
int d[maxn]; //从起点到i的距离
int cur[maxn]; //当前弧下标
void init()
{
for (int i=0;i<=n*m*2+2;i++)
G[i].clear();
edges.clear();
}
void AddEdge(int from,int to,int cap)
{
edges.push_back(Edge(from,to,cap,0));
edges.push_back(Edge(to,from,0,0)); //反向弧
int mm=edges.size();
G[from].push_back(mm-2);
G[to].push_back(mm-1);
}
bool BFS()
{
memset(vis,0,sizeof(vis));
queue<int>q;
q.push(s);
d[s]=0;
vis[s]=1;
while (!q.empty())
{
int x = q.front();q.pop();
for (int i = 0;i<G[x].size();i++)
{
Edge &e = edges[G[x][i]];
if (!vis[e.to] && e.cap > e.flow)
{
vis[e.to]=1;
d[e.to] = d[x]+1;
q.push(e.to);
}
}
}
return vis[t];
}
int DFS(int x,int a)
{
if (x==t || a==0)
return a;
int flow = 0,f;
for(int &i=cur[x];i<G[x].size();i++)
{
Edge &e = edges[G[x][i]];
if (d[x]+1 == d[e.to] && (f=DFS(e.to,min(a,e.cap-e.flow)))>0)
{
e.flow+=f;
edges[G[x][i]^1].flow-=f;
flow+=f;
a-=f;
if (a==0)
break;
}
}
return flow;
}
int Maxflow(int s,int t)
{
this->s=s;
this->t=t;
int flow = 0;
while (BFS())
{
memset(cur,0,sizeof(cur));
flow+=DFS(s,INF);
}
return flow;
}
}dc;
int main()
{
scanf("%d",&T);
while (T--)
{
int d;
int sum = 0;
scanf("%d%d",&n,&d);
for (int i = 1;i<=n;i++)
{
string s;
cin >> s;
if (i==1)
{
m=s.size();
dc.init();
}
for (int j = 0;j<s.size();j++)
{
if (s[j]-'0'>0)
{
int id = (i-1)*m+j+1;
dc.AddEdge(id,id+n*m,s[j]-'0');
if (i<=d || i+d>n || j<d || j+d>=m)
{
dc.AddEdge(id+n*m,2*n*m+1,INF);
}
else
{
for (int k = 1;k<=n;k++)
for (int h = 0;h<m;h++)
{
int id1=(k-1)*m+h+1;
if (id == id1)
continue;
if (abs(i-k)+abs(j-h) <=d)
dc.AddEdge(id+n*m,id1,INF);
}
}
}
}
}
for (int i =1;i<=n;i++)
{
string s;
cin >> s;
for (int j = 0;j<s.size();j++)
{
int id = (i-1)*m+j+1;
if (s[j]=='L')
{
++sum;
dc.AddEdge(0,id,1);
}
}
}
int ans = sum-dc.Maxflow(0,2*m*n+1);
if (!ans)
printf("Case #%d: no lizard was left behind.\n",cas++);
else if (ans==1)
printf("Case #%d: 1 lizard was left behind.\n",cas++);
else
printf("Case #%d: %d lizards were left behind.\n",cas++,ans);
}
}