bzoj1864: [Zjoi2006]三色二叉树

本文介绍了一种基于树形结构的动态规划算法实现方法,通过枚举节点颜色优化解的空间复杂度,适用于解决特定类型的组合优化问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门
大力建出树后大力dp
设f[i][j]表示以i为根节点,根节点颜色为j是的最优解。
每次枚举当前结点节点颜色和儿子颜色,
时间复杂度O(N*27)

uses math;
var
  a,b:array [0..500005,1..3] of longint;
  c:array [0..500005] of longint;
  s:ansistring;
  n,p:longint;
function searchmax(x,y:longint):longint;
  begin
    if (x>p) then p:=x;
    if (a[x,y]<=10000000) then exit(a[x,y]);
    a[x,y]:=0;
    if (s[x]='1') then begin
      if (y<>1) then a[x,y]:=max(a[x,y],searchmax(x+1,1));
      if (y<>2) then a[x,y]:=max(a[x,y],searchmax(x+1,2));
      if (y<>3) then a[x,y]:=max(a[x,y],searchmax(x+1,3));
    end;
    if (s[x]='2') then begin
      a[x,y]:=searchmax(x+1,1); a[x,y]:=0; if (c[x]=0) then c[x]:=p+1;
      if (y=1) then a[x,y]:=max(searchmax(x+1,2)+searchmax(c[x],3),searchmax(c[x],2)+searchmax(x+1,3));
      if (y=2) then a[x,y]:=max(searchmax(x+1,1)+searchmax(c[x],3),searchmax(c[x],1)+searchmax(x+1,3));
      if (y=3) then a[x,y]:=max(searchmax(x+1,1)+searchmax(c[x],2),searchmax(c[x],1)+searchmax(x+1,2));
    end;
    if (y=1) then inc(a[x,y]);
    exit(a[x,y]);
  end;
function searchmin(x,y:longint):longint;
  begin
    if (x>p) then p:=x;
    if (b[x,y]<=10000000) then exit(b[x,y]);
    if (s[x]='0') then b[x,y]:=0;
    if (s[x]='1') then begin
      if (y<>1) then b[x,y]:=min(b[x,y],searchmin(x+1,1));
      if (y<>2) then b[x,y]:=min(b[x,y],searchmin(x+1,2));
      if (y<>3) then b[x,y]:=min(b[x,y],searchmin(x+1,3));
    end;
    if (s[x]='2') then begin
      b[x,y]:=searchmin(x+1,1); b[x,y]:=10000000; if (c[x]=0) then c[x]:=p+1;
      if (y=1) then b[x,y]:=min(searchmin(x+1,2)+searchmin(c[x],3),searchmin(c[x],2)+searchmin(x+1,3));
      if (y=2) then b[x,y]:=min(searchmin(x+1,1)+searchmin(c[x],3),searchmin(c[x],1)+searchmin(x+1,3));
      if (y=3) then b[x,y]:=min(searchmin(x+1,1)+searchmin(c[x],2),searchmin(c[x],1)+searchmin(x+1,2));
    end;
    if (y=1) then inc(b[x,y]);
    exit(b[x,y]);
  end;
begin
  readln(s);
  n:=length(s);
  fillchar(a,sizeof(a),1);
  fillchar(b,sizeof(b),1);
  write(max(searchmax(1,1),max(searchmax(1,2),searchmax(1,3))),' ');
  p:=0;
  write(min(searchmin(1,1),min(searchmin(1,2),searchmin(1,3))));
end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值