传送门:www.wikioi.com/problem/1036/
滚回新校1week回来做点康复训练,话说进队爷们都在隔壁虐题,我等蒟蒻被题虐……
又是LCA,我TM就是链剖!!
Code:
//ID:zky
#include<vector>
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=30010;
typedef pair<int,int> pii;
int w[maxn],fa[maxn],son[maxn],top[maxn],dep[maxn],siz[maxn],z;
vector<int>G[maxn];
void add(int u,int v){
G[u].push_back(v);
G[v].push_back(u);
}
void dfs(int u){
son[u]=0;
siz[u]=1;
for(int i=0;i<G[u].size();i++){
int v=G[u][i];
if(v!=fa[u]){
fa[v]=u;
dep[v]=dep[u]+1;
dfs(v);
siz[u]+=siz[v];
if(siz[son[u]]<siz[v])son[u]=v;
}
}
}
void build(int u,int tp){
w[u]=++z;top[u]=tp;
if(son[u])build(son[u],tp);
for(int i=0;i<G[u].size();i++){
int v=G[u][i];
if(v!=fa[u]&&v!=son[u])
build(v,v);
}
}
int abs(int x){return x>0?x:-x;}
int len(int u,int v){
int ans=0;
while(top[u]!=top[v]){
if(dep[top[u]]>dep[top[v]]){
int a=dep[u],b=dep[top[u]];
ans+=abs(a-b)+1;
u=fa[top[u]];
}else{
int a=dep[v],b=dep[top[v]];
ans+=abs(a-b)+1;
v=fa[top[v]];
}
}
ans+=abs(dep[u]-dep[v]);
return ans;
}
int q[maxn];
int n,m;
int main(){
scanf("%d",&n);
for(int i=1;i<n;i++){
int u,v;scanf("%d%d",&u,&v);
add(u,v);
}
dfs(1);build(1,1);
scanf("%d",&m);
scanf("%d",&q[1]);
long long ans=0;
for(int i=2;i<=m;i++){
scanf("%d",&q[i]);
ans+=len(q[i-1],q[i]);
}
cout<<ans<<endl;
return 0;
}