本题考查使用了lca算法
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int N=1e5+10,M=2*N;
int h[N],ne[M],e[M],idx;
LL dist[N],w[M];
int fa[N][22];
int depth[N];
int query[N];
LL res[N],ans[N];
void add(int a,int b,int c)
{
e[idx]=b,ne[idx]=h[a],w[idx]=c,h[a]=idx++;
}
int n,m,root,cnt;
void bfs(int root)
{
memset(depth,0x3f,sizeof depth);
depth[0]=0,depth[root]=1;
queue<int> q;
q.push(root);
while(!q.empty())
{
int t=q.front(); q.pop();
for(int i=h[t];~i;i=ne[i])
{
int j=e[i];
if(depth[j]>depth[t]+1)
{
depth[j]=depth[t]+1;
fa[j][0]=t;
for(int k=1;k<=20;k++)
fa[j][k]=fa[fa[j][k-1]][k-1];
q.push(j);
}
}
}
}
LL lca(int a,int b)
{
int la=a,lb=b;
if(depth[a]<depth[b]) swap(a,b);
for(int k=20;k>=0;k--)
if(depth[fa[a][k]]>=depth[b])
a=fa[a][k];
if(a==b) return dist[la]+dist[lb]-2*dist[a];
for(int k=20;k>=0;k--)
if(fa[a][k]!=fa[b][k])
{
a=fa[a][k];
b=fa[b][k];
}
return dist[la]+dist[lb]-2*dist[fa[a][0]];
}
void dfs(int u,int fa)
{
for(int i=h[u];~i;i=ne[i])
{
int j=e[i];
if(j==fa) continue;
dist[j]=dist[u]+w[i];
dfs(j,u);
}
}
int main ()
{
ios::sync_with_stdio(0);
cin.tie(0),cout.tie(0);
cin>>n>>m;
memset(h, -1, sizeof h);
for(int i=1;i<n;i++)
{
int a,b,c; cin>>a>>b>>c;
add(a,b,c),add(b,a,c);
}
dfs(1,-1);
bfs(1);
for(int i=1;i<=m;i++)
{
cin>>query[i];
}
LL sum=0;
for(int i=2;i<=m;i++)
{
res[i]=lca(query[i-1],query[i]);
sum+=res[i];
if(i<m)
ans[i]=lca(query[i-1],query[i+1]);
}
cout<<sum-res[2]<<" ";
for(int i=2;i<m;i++)
cout<<sum-res[i]-res[i+1]+ans[i]<<" ";
cout<<sum-res[m]<<" ";
return 0;
}