【距离GDKOI:44天&GDOI:107天】【BZOJ1040】[ZJOI2008] 骑士 (环套树DP)

时间:2022-03-31 11:38:47

其实已经准备退役了,但GDOI之前还是会继续学下去的!!当成兴趣在学,已经对竞赛失去信心了的样子,我还是回去跪跪文化课吧QAQ

第一道环套树DP...其实思想挺简单的,就把环拆开,分类处理。若拆成开的两个点是u,v,dp[i,0..1]分别表示第i位骑士不选和选

(1) 不选u,v点随意    (2)u随意,v点不选...

分类dp处理即可

 const maxn=;
type
edgetype=record
toward,next:longint;
end; var
edge:array[..maxn*] of edgetype;
first:array[..maxn] of longint;
val:array[..maxn] of int64;
dp:array[..maxn,..] of int64;
pd,vb,vc:array[..maxn] of boolean;
root,vv,e,tot:longint;
n:longint;
function max(x,y:int64):int64; begin if x>y then exit(x) else exit(y); end; procedure addedge(i,j:longint);
begin
edge[tot].toward:=j;
edge[tot].next:=first[i];
first[i]:=tot;
inc(tot);
end; procedure add(i,j:longint);
begin
addedge(i,j); addedge(j,i);
end; procedure dfs(v,fa:longint);
var i,tmp:longint;
begin
pd[v]:=true;
i:=first[v];
while i<>- do
begin
tmp:=edge[i].toward;
if not pd[tmp] then dfs(tmp,v)
else if tmp<>fa then
begin
vv:=v;
root:=tmp;
e:=i;
end;
i:=edge[i].next;
end;
end; procedure dpb(v:longint); //ban u
var i,tmp:longint;
begin
dp[v,]:=; dp[v,]:=val[v]; vb[v]:=true;
i:=first[v];
while i<>- do
begin
tmp:=edge[i].toward;
if (i<>e) and (i xor <>e) and not vb[tmp] then
begin
dpb(tmp);
dp[v,]:=dp[v,]+max(dp[tmp,],dp[tmp,]);
dp[v,]:=dp[v,]+dp[tmp,];
end;
i:=edge[i].next;
end;
end; procedure dpc(v:longint); //ban v;
var i,tmp:longint;
begin
dp[v,]:=; dp[v,]:=val[v]; vc[v]:=true;
i:=first[v];
while i<>- do
begin
tmp:=edge[i].toward;
if (i<>e) and (i xor <>e) and not vc[tmp] then
begin
dpc(tmp);
dp[v,]:=dp[v,]+dp[tmp,];
if tmp=vv then dp[v,]:=dp[v,]+dp[tmp,]
else dp[v,]:=dp[v,]+max(dp[tmp,],dp[tmp,]);
end;
i:=edge[i].next;
end;
end; procedure solve;
var i:longint;
rec,ans:int64;
begin
ans:=;
for i:= to n do
if not pd[i] then
begin
rec:=; root:=-; dfs(i,-);
dpb(root); rec:=dp[root,];
dpc(root); rec:=max(rec,max(dp[root,],dp[root,]));
inc(ans,rec);
end;
writeln(ans);
end; procedure init;
var i,x:longint;
begin
fillchar(first,sizeof(first),);
readln(n);
tot:=;
for i:= to n do
begin
readln(val[i],x);
add(i,x);
end;
end; Begin
init;
solve;
End.