3361: [Usaco2004 Jan]培根距离

时间:2023-03-09 03:11:07
3361: [Usaco2004 Jan]培根距离

3361: [Usaco2004 Jan]培根距离

Time Limit: 10 Sec  Memory Limit: 128 MB
Submit: 16  Solved: 13
[Submit][Status][Discuss]

Description

    贝茜和其他奶牛联系是通过一连串的中间奶牛传递的,所以当第一头牛和贝茜联系,第二头牛和第一头牛联系,第三头牛和第二头牛联系,…一贝茜就能依次联系到其中的每一头奶牛. 联系长度是指传递过程中涉及的奶牛的数目(不包括贝茜).任何一头奶牛(不包括贝茜)的培根距离是指从贝茜到该奶牛的最小联系长度.最小的培根距离是1(当贝茜能够直接与该奶牛联系时).约输有C头牛,编号1到C,贝茜是1号.有P(1≤P≤10000)组奶牛相互联系.请找到最大的培根距离.

Input

    第1行:C和P.
    第2到P+1行:每行两头牛,它们之间有联系.

Output

    输出最大培根距离.

Sample Input

6 7
1 2
2 3
2 4
3 4
3 5
4 5
6 5

Sample Output

4
样例说明
从贝茜到6奶牛的距离是4.联系路径(2,4,5,6)和(2,3,5,6)都适合

HINT

Source

Orange

题解:spfa模板题,水水哒

在这个里面加入了一个新的优化方法,昨天在wnjxyk的空间里面看到的(OTLwnjxyk),在spfa入队前,可以在队列内的值进行判重操作,这样子可以提高速度,而且必要时可以起到压缩队列所用空间的作用,可以将队列有效长度控制在N以内,这样子必要时只需要开一个循环队列即可解决空间问题,GET!!!(OTLwnjxyk)

 type
point=^node;
node=record
g,w:longint;
next:point;
end;
var
i,j,k,l,m,n,f,r:longint;
p:point;
a:array[..] of point;
b,c:array[..] of longint;
d:array[..] of longint;
procedure add(x,y,z:longint);inline;
var p:point;
begin
new(p);p^.g:=y;p^.w:=z;
p^.next:=a[x];a[x]:=p;
end;
begin
readln(n,m);
for i:= to n do a[i]:=nil;
for i:= to m do
begin
readln(j,k);
add(j,k,);add(k,j,);
end;
fillchar(b,sizeof(b),);
fillchar(c,sizeof(c),);
fillchar(d,sizeof(d),);
f:=;r:=;
d[]:=;c[]:=;b[]:=;
while f<r do
begin
p:=a[d[f]];
while p<>nil do
begin
if ((b[p^.g]=) or ((b[p^.g]=) and (b[p^.g]>(b[d[f]]+p^.w)))) and (c[p^.g]=) then
begin
b[p^.g]:=b[d[f]]+p^.w;
c[p^.g]:=;
d[r]:=p^.g;
inc(r);
end;
p:=p^.next;
end;
c[d[f]]:=;
inc(f);
end;
for i:= to n do dec(b[i]);
l:=;
for i:= to n do if b[i]>l then l:=b[i];
writeln(l);
end.