Description
司令部的将军们打算在N*M的网格地图上部署他们的炮兵部队。一个N*M的地图由N行M列组成,地图的每一格可能是山地(用“H” 表示),也可能是平原(用“P”表示),如下图。在每一格平原地形上最多可以布置一支炮兵部队(山地上不能够部署炮兵部队);一支炮兵部队在地图上的攻击范围如图中黑色区域所示:
如果在地图中的灰色所标识的平原上部署一支炮兵部队,则图中的黑色的网格表示它能够攻击到的区域:沿横向左右各两格,沿纵向上下各两格。图上其它白色网格均攻击不到。从图上可见炮兵的攻击范围不受地形的影响。
现在,将军们规划如何部署炮兵部队,在防止误伤的前提下(保证任何两支炮兵部队之间不能互相攻击,即任何一支炮兵部队都不在其他支炮兵部队的攻击范围内),在整个地图区域内最多能够摆放多少我军的炮兵部队。
Input
第一行包含两个由空格分割开的正整数,分别表示N和M;
接下来的N行,每一行含有连续的M个字符(‘P’或者‘H’),中间没有空格。按顺序表示地图中每一行的数据。N≤100;M≤10。
Output
仅在第一行包含一个整数K,表示最多能摆放的炮兵部队的数量。
Sample Input
5 4
PHPP
PPHH
PPPP
PHPP
PHHP
Sample Output
6
解题思路:
首先DFS出每一行能放置的状态。
用f[i,j,k]表示第i行状态为j,i-1行状态为k能放置的最多炮兵;f[i,j,k]=max(f[i-1,k,l]+b[j])且满足j、k、l三种状态不冲突,b[j]为第j种状态下的士兵数量。
var
a,b,c,d:array[1..100]of longint;
f:array[0..100,0..100,0..100]of longint;
n,m,i,j,k,l,ans,s,t:longint;
ch:char;
procedure dfs(dep:longint);
var
i:longint;
begin
if dep>m then
begin
inc(t);
for i:=1 to m do
begin
a[t]:=a[t]+(1 shl (i-1))*d[i];
inc(b[t],d[i]);
end;
exit;
end;
dfs(dep+1); d[dep]:=1;
dfs(dep+3); d[dep]:=0;
end;
begin
readln(n,m);
for i:=1 to n do
for j:=1 to m do
begin
if j<m then read(ch) else readln(ch);
if ch='H' then c[i]:=c[i]+1 shl (j-1);
end;
dfs(1);
if n=1 then
begin
for i:=1 to t do
if (a[i] and c[1]=0) and (b[i]>ans) then ans:=b[i];
writeln(ans); halt;
end;
for i:=1 to t do
for j:=1 to t do
if (a[i] and c[1]=0) and (a[j] and c[2]=0) and (a[i] and a[j]=0) then f[2,j,i]:=b[j]+b[i];
for i:=3 to n do
for j:=1 to t do
begin
if a[j] and c[i]<>0 then continue;
for k:=1 to t do
begin
if (a[k] and c[i-1]<>0) or (a[k] and a[j]<>0)then continue;
for l:=1 to t do
begin
if (a[l] and c[i-2]<>0) or (a[l] and a[k]<>0) or (a[l] and a[j]<>0) then continue;
if f[i-1,k,l]+b[j]>f[i,j,k] then f[i,j,k]:=f[i-1,k,l]+b[j];
end;
end;
end;
for i:=1 to t do
for j:=1 to t do
if f[n,i,j]>ans then ans:=f[n,i,j];
writeln(ans);
end.