bzoj1032: [JSOI2007]祖码Zuma

区间dp

先把连续相同的珠子压缩

1.可把[l,r]断成[l,i]U(i,r]

2.若两端点的值相同,考虑消去中间的珠子使两端点在一起

const
  maxn=500;
var
  m,n,i,a0,last:integer;
  a:array [1..maxn] of record
      data,num:integer;
    end;
  f:array [1..maxn,1..maxn] of integer;

function min(a,b:integer):integer;
begin
  if a>b then
    exit(b)
  else
    exit(a);
end;

function how(x:integer):integer;
begin
  if x<=2 then
    exit(3-x);
  exit(1);
end;

function dp(l,r:integer):integer;
var
  ans,i:integer;
begin
  if f[l,r]<>-1 then
    exit(f[l,r]);
  if l=r then
    exit(how(a[l].num));
  ans:=maxint;
  if a[l].data=a[r].data then
  begin
    if a[l].num+a[r].num>=3 then
      ans:=dp(l+1,r-1)
    else
      ans:=dp(l+1,r-1)+1;
  end;
  for i:=l to r-1 do
    ans:=min(ans,dp(l,i)+dp(i+1,r));
  f[l,r]:=ans;
  exit(ans);
end;

begin
  readln(n);
  m:=0;
  last:=-1;
  for i:=1 to n do
  begin
    read(a0);
    if a0<>last then
    begin
      inc(m);
      a[m].data:=a0;
      a[m].num:=1;
      last:=a0;
    end
    else
      inc(a[m].num);
  end;
  fillchar(f,sizeof(f),$ff);
  writeln(dp(1,m));
end.


阅读更多
想对作者说点什么? 我来说一句
相关热词

没有更多推荐了,返回首页