Description
Consider a tree with N vertices, numbered from 1 to N. Add, if it is possible, a minimum number of edges thus every vertex belongs to exactly one cycle.
Input
The input has the following structure:
N
x(1) y(1)
x(2) y(2)
...
x(N-1) y(n-1)
N (3 <= N <=100) is the number of vertices. x(i) and y(i) (x(i), y(i) are integers, 1 <= x(i), y(i) <= N) represent the two vertices connected by the i-th edge.
N
x(1) y(1)
x(2) y(2)
...
x(N-1) y(n-1)
N (3 <= N <=100) is the number of vertices. x(i) and y(i) (x(i), y(i) are integers, 1 <= x(i), y(i) <= N) represent the two vertices connected by the i-th edge.
Output
The output will contain the value -1 if the problem doesn't have a solution, otherwise an integer, representing the number of added edges.
Sample Input
7 1 2 1 3 3 5 3 4 5 6 5 7
Sample Output
2
题目大意:给定一棵树,求最少添加多少条边使得每个点都在且仅在一个环上。环的长度最小为3。
//===================================================================================
树形DP。
设f[i,0],f[i,1],f[i,2]分别为以i为根的子树:全部成环、除根以为全部成环、除一条与根相连的长度大于等于2的链外全部成环的最小添加条数。f[i,3]用来简化的,记录的是min(f[i,1],f[i,2])。
状态转移:
f[i,0]=min(min(f[x,3]+f[y,3]+1+all-f[x,0]-f[y,0]),min(f[v,2]+1+all-f[v,0]),f[i,0])
x,y,v是i的儿子,all是所有f[x,0]的和(x是i的儿子,下同)。
f[i,1]=min(f[i,1],all)
f[i,2]=min(f[i,2],f[j,3]+all-f[i,0]) //f[i,3]的简化作用就是这个了。。。
f[i,3]=min(f[i,1],f[i,2])
初值要赋成极大值。
AC CODE
program pku_1848;
const maxn=maxlongint div 110;
var f:array[1..100,0..3] of longint;
son:array[1..100,0..100] of longint;
line,next:array[1..200] of longint;
en:array[1..100] of longint;
p:array[1..100] of boolean;
n,ans,len:longint;
//============================================================================
procedure ins(x,y:longint);
begin
inc(len); line[len]:=y;
next[len]:=en[x]; en[x]:=len;
end;
//============================================================================
procedure init;
var i,x,y:longint;
begin
readln(n);
for i:=1 to n-1 do
begin
readln(x,y);
ins(x,y); ins(y,x);
end;
end;
//============================================================================
procedure dp(u:longint);
var i,j,x,y,v,tmp,all:longint;
begin
i:=en[u]; p[u]:=true;
while i<>0 do
begin v:=line[i];
if not(p[v]) then
begin
dp(v); inc(son[u,0]);
son[u,son[u,0]]:=v;
end; i:=next[i];
end;
if son[u,0]=0 then
begin
f[u,0]:=maxn; f[u,1]:=0;
f[u,2]:=maxn; f[u,3]:=0;
exit;
end; all:=0;
for i:=1 to son[u,0] do inc(all,f[son[u,i],0]);
f[u,0]:=maxn; f[u,1]:=maxn; f[u,2]:=maxn;
if all<f[u,1] then f[u,1]:=all;
for i:=1 to son[u,0] do
for j:=i+1 to son[u,0] do
begin
x:=son[u,i]; y:=son[u,j];
tmp:=all-f[x,0]-f[y,0];
if f[x,3]+f[y,3]+1+tmp<f[u,0] then
f[u,0]:=f[x,3]+f[y,3]+1+tmp;
end;
for i:=1 to son[u,0] do
begin v:=son[u,i];
tmp:=all-f[v,0];
if f[v,2]+1+tmp<f[u,0] then
f[u,0]:=f[v,2]+1+tmp;
if f[v,3]+tmp<f[u,2] then
f[u,2]:=f[v,3]+tmp;
end;
if f[u,1]<f[u,2] then f[u,3]:=f[u,1] else
f[u,3]:=f[u,2];
end;
//============================================================================
begin
init;
dp(1);
if f[1,0]=maxn then writeln('-1') else
writeln(f[1,0]);
end.