"Business travel" problem Solving report
By MPs
"Title 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.
"Input description"
the first line in the input file has an integer n, 1<=n<=30 000, 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"
Export the shortest time a merchant travels in the output file
"Input Sample"
5
1 2
1 5
3 5
4 5
4
1
3
2
5
"Output Example"
7
Analysis
Mathematical modeling: Build a tree, find the shortest path on each tree, algorithm LCA
Shortest path of two points =d (x) +d (y) -2*d (LCA (x, y))
D is the shortest path to the root point
Obviously, that's the depth of the point.
It can be calculated by multiplying, and then it's OK to simulate it directly.
Code
1#include <iostream>2#include <cstdio>3#include <cstring>4#include <algorithm>5 using namespacestd;6 7 Const intmaxn=70001;8 9 intdeep[maxn],p[maxn][ -];Ten intn,q; One A structlist{ - intTo,next; - }E[MAXN]; the intHead[maxn],cnt=0; - - voidAddedge (intUintv) { -cnt++; +e[cnt].to=v; -e[cnt].next=Head[u]; +head[u]=CNT; A } at - voidinit () { -Freopen ("trip.in","R", stdin); -Freopen ("Trip.out","W", stdout); -scanf"%d",&n); - inti,u,v; in for(i=1; i<n;i++){ -scanf"%d%d",&u,&v); to Addedge (u,v); + Addedge (v,u); - } the } * $ intLcaintUintv) {Panax Notoginseng if(deep[u]<Deep[v]) swap (U,V); - intc=deep[u]-deep[v],i; the for(i=0; i<= at; i++) + if((1<<i) &c) Au=P[u][i]; the for(i= at; i>=0; i--) + if(p[u][i]!=P[v][i]) { -u=P[u][i]; $v=P[v][i]; $ } - if(U==V)returnu; - Else returnp[u][0]; the } - Wuyi voidDfsintu) { the inti; - for(i=1; i<= at; i++){ Wu if(deep[u]< (1<<i)) Break; -p[u][i]=p[p[u][i-1]][i-1]; About } $ for(i=head[u];i;i=e[i].next) - if(!Deep[e[i].to]) { -deep[e[i].to]=deep[u]+1; -p[e[i].to][0]=u; A DFS (e[i].to); + } the } - $ voidsolve () { thescanf"%d",&q); the inti,u,v,ans=0, LCA; the for(i=1; i<=n;i++) the if(!Deep[i]) { -p[i][0]=i; indeep[i]=1; the DFS (i); the } Aboutscanf"%d",&u); the for(i=2; i<=q;i++){ thescanf"%d",&v); theLca=LCA (U,V); +ans+=deep[u]+deep[v]-2*Deep[lca]; -u=v; the }Bayiprintf"%d", ans); the } the - intMain () { - init (); the solve (); the return 0; the}
"Business travel" problem Solving report