POJ 3254:Corn Fields(状态压缩DP)

题目大意:一个矩形的草地,分为多个格子,有的格子可以有奶牛(标为1),有的格子不可以放置奶牛(标为0),计算摆放奶牛的方案数。

分析:

   f[i,j]表示第i行状态为j的方案总数。

  状态转移方程f[i,j]=∑f[i-1,k](k为所有满足条件的状态)。

  边界f[1,i]=1(i为满足条件的状态)。

  题目要求有两点1.只在标记为1的地方放牛2.相邻格子只能一个有牛。

代码:

program cowfood;
var
  a,b:array[0..4096]of int64;
  f:array[0..12,0..4096]of int64;
  n,m,x,t,len,ans:int64; i,j,k:longint;
procedure work;
var i:longint;
begin
 len:=0;
  for i:=0 to 1 shl m-1 do
   if (i and (i<<1))=0 then begin  inc(len);  b[len]:=i; end;
end;
function cheak(x,y:longint):boolean;
begin
  if (a[x] and b[y])=0 then exit(true) else exit(false);
end;
begin
  assign(input,'cowfood.in');
  reset(input);
  assign(output,'cowfood.out');
  rewrite(output);
  readln(n,m);
  k:=1 shl (m-1);
  for i:=1 to n do
   begin   t:=k;
     for j:=1 to m do
      begin
        read(x);inc(a[i],t*(1-x));  t:=t shr 1;
      end;
     readln;
   end;
 work;
  for i:=1 to len do  if cheak(1,i) then f[1,b[i]]:=1;
  for i:=2 to n do
   for j:=1 to len do
    if cheak(i,j) then
     for k:=1 to len do
        if (b[j]and b[k]=0)and(cheak(i-1,k))  then
         f[i,b[j]]:=(f[i,b[j]]+f[i-1,b[k]])mod 100000000;
  for i:=1 to len do
  ans:=(ans+f[n,b[i]])mod 100000000;
  writeln(ans);
  close(input); close(output);
end. 
View Code

 

posted @ 2015-12-26 20:59  QTY_YTQ  阅读(141)  评论(0)    收藏  举报