题目链接:http://www.lydsy.com/JudgeOnline/problem.php?id=2657
树形dp,注意建图,刷两次最长路。
贴代码:
const maxn=200005;
var son,next,id,sonp,nextp:array[0..maxn*6]of longint;
link,linkp,f,que:array[0..maxn]of longint;
vis:array[0..maxn]of boolean;
n,tot,totp,head,tail:longint;
procedure addp(x,y:longint);
begin
inc(totp);sonp[totp]:=y;nextp[totp]:=linkp[x];linkp[x]:=totp;
end;
procedure add(x,y,z:longint);
begin
inc(tot);son[tot]:=y;next[tot]:=link[x];link[x]:=tot;id[tot]:=z;
end;
procedure build(x,y,z,k:longint);
var j:longint;
xy,xz,yz:boolean;
begin
xy:=false;xz:=false;yz:=false;
j:=link[x];
while j<>0 do
begin
if son[j]=y then begin addp(k,id[j]);addp(id[j],k);xy:=true; end;
if son[j]=z then begin addp(k,id[j]);addp(id[j],k);xz:=true; end;
j:=next[j];
end;
j:=link[y];
while j<>0 do
begin
if son[j]=z then begin addp(k,id[j]);addp(id[j],k);yz:=true; end;
j:=next[j];
end;
if not xy then begin add(x,y,k);add(y,x,k); end;
if not xz then begin add(x,z,k);add(z,x,k); end;
if not yz then begin add(y,z,k);add(z,y,k); end;
end;
procedure init;
var i,j,x,y,z:longint;
begin
assign(input,'journey.in');reset(input);
assign(output,'journey.out');rewrite(output);
readln(n);
fillchar(link,sizeof(link),0);
fillchar(linkp,sizeof(linkp),0);
tot:=0;totp:=0;
for i:=1 to n-2 do
begin
readln(x,y,z);
build(x,y,z,i);
end;
end;
procedure spfa(s:longint;var maxid:longint);
var i,j,x,max:longint;
begin
fillchar(vis,sizeof(vis),0);
fillchar(f,sizeof(f),0);
head:=0;tail:=1;que[1]:=s;vis[s]:=true;
while head<>tail do
begin
head:=(head+1)mod maxn;
x:=que[head];
j:=linkp[x];
while j<>0 do
begin
if f[x]+1>f[sonp[j]] then begin
f[sonp[j]]:=f[x]+1;
if not vis[sonp[j]] then begin
vis[sonp[j]]:=true;
inc(tail);
que[tail]:=sonp[j];
end;
end;
j:=nextp[j];
end;
end;
max:=0;maxid:=0;
for i:=1 to n-2 do
if f[i]>max then begin
max:=f[i];maxid:=i;
end;
end;
procedure print;
var k,k1:longint;
begin
k:=0;k1:=0;
spfa(1,k);
spfa(k,k1);
writeln(f[k1]+1);
close(input);close(output);
end;
begin
init;
print;
end.
【写的有漏洞的,欢迎路过大神吐槽】
2017/2/13 18:39:58
Ending.