![2953: [Poi2002]商务旅行 2953: [Poi2002]商务旅行](https://image.shishitao.com:8440/aHR0cHM6Ly9ia3FzaW1nLmlrYWZhbi5jb20vdXBsb2FkL2NoYXRncHQtcy5wbmc%2FIQ%3D%3D.png?!?w=700&webp=1)
2953: [Poi2002]商务旅行
Time Limit: 3 Sec Memory Limit: 128 MB
Submit: 8 Solved: 8
[Submit][Status]
Description
某首都城市的商人要经常到各城镇去做生意,他们按自己的路线去做,目的是为了更好的节约时间。
假设有N个城镇,首都编号为1,商人从首都出发,其他各城镇之间都有道路连接,任意两个城镇之间如果有直连道路,在他们之间行驶需要花费单位时间。该国公路网络发达,从首都出发能到达任意一个城镇,并且公路网络不会存在环。
你的任务是帮助该商人计算一下他的最短旅行时间。
Input
第一行有一个整数N,1<=n<=30 000,为城镇的数目。下面N-1行,每行由两个整数a 和b (1<=a, b<=n; a<>b)组成,表示城镇a和城镇b有公路连接。在第N+1行为一个整数M,下面的M行,每行有该商人需要顺次经过的各城镇编号。
Output
输出该商人旅行的最短时间。
Sample Input
5
1 2
1 5
3 5
4 5
4
1
3
2
5
1 2
1 5
3 5
4 5
4
1
3
2
5
Sample Output
7
HINT
Source
题解:本来想在codevs做一道线段树题目的,可是进入线段树分类后就发现了这个(HansBug:呵呵呵呵这个也叫线段树我也是醉了)只要学过LCA的童鞋不难发现这就是一个最裸的LCA,直接上倍增搞搞就行了,连加上边长数组都免了。。。
type
point=^node;
node=record
g:longint;
next:point;
end; var
i,j,k,l,m,n,t:longint;
a:array[..] of point;
c:array[..,..] of longint;
d:array[..] of longint;
function min(x,y:longint):longint;inline;
begin
if x<y then min:=x else min:=y;
end;
function max(x,y:longint):longint;inline;
begin
if x>y then max:=x else max:=y;
end;
procedure swap(var x,y:longint);inline;
var z:longint;
begin
z:=x;x:=y;y:=z;
end;
procedure add(x,y:longint);inline;
var p:point;
begin
new(p);
p^.g:=y;
p^.next:=a[x];
a[x]:=p;
end;
procedure dfs(x:longint);inline;
var p:point;
begin
p:=a[x];
while p<>nil do
begin
if c[,p^.g]= then
begin
c[,p^.g]:=x;
d[p^.g]:=d[x]+;
dfs(p^.g);
end;
p:=p^.next;
end;
end;
function getfat(x,y:longint):longint;inline;
var i,j,k:longint;
begin
i:=;
while y> do
begin
if odd(y) then x:=c[i,x];
inc(i);y:=y div ;
end;
getfat:=x;
end;
function dis(x,y:longint):longint;
var
a1,a2,a3,i,j,k,l:longint;
begin
if d[x]<d[y] then swap(x,y);
a1:=x;a2:=y;
x:=getfat(x,d[x]-d[y]);
if x=y then exit(d[a1]-d[a2]);
for i:= downto do
begin
if c[i,x]= then continue;
if c[i,x]<>c[i,y] then
begin
x:=c[i,x];
y:=c[i,y];
end
end;
a3:=c[,x];
exit(d[a1]+d[a2]-d[a3]-d[a3]);
end; begin
readln(n);
for i:= to n do a[i]:=nil;
for i:= to n- do
begin
readln(j,k);
add(j,k);add(k,j);
end;
fillchar(c,sizeof(c),);
fillchar(d,sizeof(d),);
c[,]:=-;
dfs();c[,]:=;
for i:= to do
for j:= to n do
c[i,j]:=c[i-,c[i-,j]];
readln(m);
readln(j);l:=;
for i:= to m- do
begin
k:=j;
readln(j);
t:=dis(k,j);
l:=l+t;
end;
writeln(l);
readln;
end.