Codevs 1036 Business Traveltime limit: 1 sspace limit: 128000 KBtitle level: Diamonds DiamondTitle Description
Description
A businessman in a capital city often goes to the towns to do business, and they do it on their own lines to save time.
Suppose there are N towns, the capital is numbered 1, the merchant departs from the capital, there are road connections between the other towns, and if there are direct links between any two towns, it takes a unit of time to travel between them. The country has a well-developed road network, which can reach any town from the capital, and the road network will not be a ring.
Your task is to help the businessman calculate his shortest travel time.
Enter a description
Input Description
the first line in the input file has an integer n,1<=n<=30 000, which is the number of towns. N-1 lines below, each line consists of two integers a and b (1<=a, b<=n; a<>b), indicating that town A and town B have road connections. In the N+1 Act an integer m, the following M-line, each line has the number of towns that the merchant needs to pass sequentially.
Output description
Output Description
outputs the shortest time the merchant travels in the output file.
Sample input
Sample Input
5
1 2
1 5
3 5
4 5
4
1
3
2
5
Sample output
Sample Output
7
1 #defineN 601002#include <iostream>3 using namespacestd;4#include <cstdio>5#include <cstring>6 #defineC 207typedefLong Longll;8 intAnce[n>>1][c],dis[n>>1],n,a,b,m;9ll sum=0;Ten structedge{ One intV,last; A}edge[n<<1]; - intDeep[n>>1],head[n>>1],t=0; - voidAdd_edge (intUintv) the { -++T; -edge[t].v=v; -edge[t].last=Head[u]; +head[u]=T; - } + voidinput () A { atscanf"%d",&n); - for(intI=1; i<n;++i) - { -scanf"%d%d",&a,&b); - Add_edge (A, b); -Add_edge (B,a);/*Note that the tree must be built in both directions.*/ in } - } to voidDfsintk) + { - for(intL=head[k];l;l=edge[l].last) the { * if(!DEEP[EDGE[L].V]) $ {Panax Notoginsengdis[edge[l].v]=dis[k]+1; -ance[edge[l].v][0]=K; thedeep[edge[l].v]=deep[k]+1; + DFS (EDGE[L].V); A } the } + } - voidchuli_ance () $ { $ for(intI=1;(1<<i) <=n;++i) - for(intj=1; j<=n;++j) -ance[j][i]=ance[ance[j][i-1]][i-1]; the } - intLcaintAintb)Wuyi { the inti,j; - if(deep[a]<deep[b]) swap (A, b); Wu for(i=0;(1<<i) <=deep[a];++i); -i--; About for(j=i;j>=0;--j) $ if(Deep[a]-(1<<J) >=Deep[b]) -A=Ance[a][j]; - if(a==b)returnA; - for(j=i;j>=0;--j) A { + if(ance[a][j]!=-1&&ance[a][j]!=Ance[b][j]) the { -A=Ance[a][j]; $b=Ance[b][j]; the } the } the returnance[a][0]; the } - intMain () in { the input (); thedeep[1]=1; Aboutdis[1]=0; thememset (ance,-1,sizeof(ance)); theDfs1); the chuli_ance (); +scanf"%d",&m); -scanf"%d",&a); the intSta=A;Bayi for(intI=2; i<=m;++i) the { thescanf"%d",&b); - intzuxian=LCA (A, b); -sum+= (dis[a]+dis[b]-2*Dis[zuxian]); theA=b; the } thesum+=Dis[sta]; thecout<<sum<<Endl; - return 0; the}
Multiplication Method-lca Codevs 1036 Business trip