题目
Description
你有一个n个点m条边的森林,编号从0开始,边有边权,你现在要添加若干边权为L的边,满足:
1、最后n个点构成一颗树。
2、这棵树的直径尽量小。
请你求出这个最小的直径是多少。
Input
第一行三个整数n,m,L。
接下来m行,每行三个整数u,v,w,表示u和v之间有长为w的边。
Output
一行一个整数,表示最小直径的长度。
Sample Input
12 8 2
0 8 4
8 2 2
2 7 4
5 11 3
5 1 7
1 3 1
1 9 5
10 6 3
Sample Output
18
Data Constraint
对于20%的数据:n<=5;
对于60%的数据:n<=2000;
对于100%的数据:n<=50000,m
题解
比较感性而且显然的,我们可以先在每一颗树上找到一个离它最远的点最近的点,然后把每一颗树中的这样的点连起来变成一棵树,这棵树的直径就是最小的直径
贴代码
var
a:array[0..150005,1..3]of longint;
b:array[0..150005,1..2]of longint;
ct,now:array[0..100005]of longint;
cc:array[0..50005,1..4]of longint;
bz,bq:array[0..50005]of boolean;
h:array[0..200005]of longint;
i,j,k,l,m,n,x,y,z,t1,t2,ans,ma1,ma2:longint;
Function Max(x,y:longint):longint;
begin
if x>y then exit(x) else exit(y);
end;
procedure qsort(l,r:longint);
var
i,j,mid:longint;
begin
i:=l;
j:=r;
mid:=a[(i+j) div 2,1];
repeat
while a[i,1]<mid do inc(i);
while a[j,1]>mid do dec(j);
if i<=j then
begin
a[0]:=a[i]; a[i]:=a[j]; a[j]:=a[0];
inc(i); dec(j);
end;
until i>j;
if i<r then qsort(i,r);
if l<j then qsort(l,j);
end;
procedure star;
begin
b[a[1,1],1]:=1;
for i:=2 to m do
if a[i,1]<>a[i-1,1] then
begin
b[a[i-1,1],2]:=i-1;
b[a[i,1],1]:=i;
end;
b[a[m,1],2]:=m;
end;
procedure dfs_size(x:longint);
var
i,p:longint;
begin
bz[x]:=true;
for i:=b[x,1] to b[x,2] do
if (bz[a[i,2]]=false) and (i<>0) then
begin
dfs_size(a[i,2]);
p:=cc[a[i,2],1]+a[i,3];
if p>cc[x,1] then
begin
cc[x,3]:=cc[x,1]; cc[x,4]:=cc[x,2];
cc[x,1]:=p; cc[x,2]:=a[i,2];
end else
if p>cc[x,2] then
begin
cc[x,3]:=p;
cc[x,4]:=a[i,2];
end;
end;
end;
procedure dfs_ag(x,z:longint);
var
i,t,tt:longint;
begin
bz[x]:=true;
for i:=b[x,1] to b[x,2] do
if (bz[a[i,2]]=false) and (i<>0) then
begin
if cc[x,2]=a[i,2] then t:=cc[x,3] else t:=cc[x,1];
t:=max(t,z)+a[i,3];
tt:=max(t,cc[a[i,2],1]);
if tt<t1 then
begin
t1:=tt;
t2:=a[i,2];
end;
dfs_ag(a[i,2],t);
end;
end;
procedure bfs_go(x:longint);
var
i,j,k,s1,s2:longint;
begin
fillchar(bz,sizeof(bz),false);
fillchar(ct,sizeof(ct),0);
ans:=0;
i:=1;
j:=0;
h[1]:=x;
bz[x]:=true;
while i>j do
begin
inc(j);
s1:=h[j];
for k:=b[s1,1] to b[s1,2] do
if (bz[a[k,2]]=false) and (k<>0) then
begin
s2:=a[k,2];
ct[s2]:=ct[s1]+a[k,3];
if ct[s2]>ans then
begin
ans:=ct[s2];
t1:=s2;
end;
bz[s2]:=true;
inc(i);
h[i]:=s2;
end;
end;
end;
begin
assign(input,'diameter.in'); reset(input);
assign(output,'diameter.out'); rewrite(output);
readln(n,m,l);
for i:=1 to m do
begin
readln(x,y,z);
inc(x); inc(y);
a[i,1]:=x; a[i,2]:=y; a[i,3]:=z;
a[m+i,1]:=y; a[m+i,2]:=x; a[m+i,3]:=z;
end;
m:=m*2;
qsort(1,m);
star;
for i:=1 to n do
if (bz[i]=false) then dfs_size(i);
fillchar(bz,sizeof(bz),false);
for i:=1 to n do
if (bz[i]=false) then
begin
t1:=cc[i,1]; t2:=i;
dfs_ag(i,0);
inc(now[0]);
now[now[0]]:=t2;
end;
for i:=2 to now[0] do
begin
x:=m+i-1;
a[x,1]:=now[1]; a[x,2]:=now[i]; a[x,3]:=l;
x:=x+now[0]-1;
a[x,1]:=now[i]; a[x,2]:=now[1]; a[x,3]:=l;
end;
m:=m+(now[0]-1)*2;
qsort(1,m);
star;
bfs_go(1);
bfs_go(t1);
writeln(ans);
close(input); close(output);
end.