由于k只有2,所以我们分类讨论
显然当k=1时,我们只要连一条最长的路径即可就是树的直径L
少走了L-1条边
如果k=2时,我们再次连边成环后
如果成环路径与上一次的最长路径没有相同的边,那少走的边数是路径长l-1
如果有相同的边,那么相同的边一共还是会走两次,少走的边数是l-1-2*same
因此我们只要把第一次找的的最长路径上的边标记为-1,再做一次树形dp即可

 1 type node=record
 2        po,len,next:longint;
 3      end;
 4 
 5 var w:array[0..200010] of node;
 6     f,p1,p2,p:array[0..100010] of longint;
 7     v:array[0..100010] of boolean;
 8     i,ans,loc,maxx,t,n,k,x,y:longint;
 9 
10 function max(a,b:longint):longint;
11   begin
12     if a>b then exit(a) else exit(b);
13   end;
14 
15 procedure add(x,y:longint);
16   begin
17     inc(t);
18     w[t].po:=y;
19     w[t].len:=1;
20     w[t].next:=p[x];
21     p[x]:=t;
22   end;
23 
24 procedure dfs(x:longint);
25   var i,y,s1,s2:longint;
26   begin
27     i:=p[x];
28     v[x]:=true;
29     s1:=0;
30     s2:=0;
31     while i<>-1 do
32     begin
33       y:=w[i].po;
34       if not v[y] then
35       begin
36         dfs(y);
37         if f[y]+w[i].len>s1 then
38         begin
39           s2:=s1;
40           p2[x]:=p1[x];
41           s1:=f[y]+w[i].len;
42           p1[x]:=i;
43         end
44         else if (s2<f[y]+w[i].len) then
45         begin
46           s2:=f[y]+w[i].len;
47           p2[x]:=i;
48         end;
49       end;
50       i:=w[i].next;
51     end;
52  //   writeln(x,' ',s1,' ',s2);
53     f[x]:=s1;
54     if maxx<s1+s2 then
55     begin
56       maxx:=s1+s2;
57       loc:=x;
58     end;
59   end;
60 
61 begin
62   t:=-1;
63   fillchar(p,sizeof(p),255);
64   fillchar(p1,sizeof(p1),255);
65   fillchar(p2,sizeof(p2),255);
66   readln(n,k);
67   for i:=1 to n-1 do
68   begin
69     readln(x,y);
70     add(x,y);
71     add(y,x);
72   end;
73   dfs(1);
74   ans:=2*(n-1)-maxx+1;
75   if k=2 then
76   begin
77     maxx:=0;
78     w[p1[loc]].len:=-1;
79     w[p2[loc]].len:=-1;
80     x:=w[p1[loc]].po;
81     while p1[x]<>-1 do
82     begin
83       w[p1[x]].len:=-1;
84       x:=w[p1[x]].po;
85     end;
86     x:=w[p2[loc]].po;
87     while p1[x]<>-1 do
88     begin
89       w[p1[x]].len:=-1;
90       x:=w[p1[x]].po;
91     end;
92     fillchar(v,sizeof(v),false);
93     fillchar(f,sizeof(f),0);
94     dfs(1);
95     ans:=ans-maxx+1;
96   end;
97   writeln(ans);
98 end.
View Code

 

posted on 2015-01-09 22:40  acphile  阅读(195)  评论(0编辑  收藏  举报