# Factory

Accepts: 100
Submissions: 383
Time Limit: 20000/10000 MS (Java/Others)
Memory Limit: 132768/132768 K (Java/Others) Problem Description

Input

【数据范围】

0<=边权<=100

1<=N,M,Q,工厂总数<=100000

Output

Sample Input Copy

```1
3 3
1 2 1
2 3 1
2 1 1
2 2 3
2 1 3
3
1 2
2 3
1 3
```

Sample Output Copy

```1
0
0
```

``````#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
#define inf 0x3f3f3f3f
using namespace std;
int fa[100010],anc[100010][32],deep[100010],dis[100010];
struct node{
int to,val;
};
vector<struct node>edge[100010];
vector<int>vec[100010];
int T,n,m;
void dfs(int x){
anc[x][0]=fa[x];
for(int i=1;i<=31;i++)
anc[x][i]=anc[anc[x][i-1]][i-1];
int len=edge[x].size();
for(int i=0;i<len;i++){
struct node next=edge[x][i];
if(next.to!=fa[x]){
fa[next.to]=x;
deep[next.to]=deep[x]+1;
dis[next.to]=dis[x]+next.val;
dfs(next.to);
}
}
}
int LCA(int x,int y){
if(deep[x]<deep[y])
swap(x,y);
for(int i=31;i>=0;i--){
if(deep[y]<=deep[anc[x][i]]){
x=anc[x][i];
}
}
if(x==y)
return x;
for(int i=31;i>=0;i--){
if(anc[x][i]!=anc[y][i]){
x=anc[x][i];
y=anc[y][i];
}
}
return anc[x][0];
}
void Init(){
for(int i=0;i<=n;i++){
edge[i].clear();
vec[i].clear();
}
memset(fa,0,sizeof(fa));
memset(anc,0,sizeof(anc));
}
int main(){
scanf("%d",&T);
while(T--){
int u,v,w;
scanf("%d%d",&n,&m);
Init();
for(int i=1;i<n;i++){
scanf("%d%d%d",&u,&v,&w);
edge[u].push_back((node){v,w});
edge[v].push_back((node){u,w});
}
for(int i=1;i<=m;i++){
int x;
scanf("%d",&x);
for(int j=1;j<=x;j++){
int y;
scanf("%d",&y);
vec[i].push_back(y);
}
}
fa[1]=1;
dfs(1);
//for(int i=1;i<=n;i++){
//    printf("%d ",dis[i]);
//}
//cout<<endl;
int q;
scanf("%d",&q);
while(q--){
int ans=inf;
scanf("%d%d",&u,&v);
int l1=vec[u].size();
int l2=vec[v].size();
for(int i=0;i<l1;i++){
for(int j=0;j<l2;j++){
int lca=LCA(vec[u][i],vec[v][j]);
//printf("%d\n",lca);
ans=min(ans,dis[vec[u][i]]+dis[vec[v][j]]-dis[lca]*2);
}
}
printf("%d\n",ans);
}
}
return 0;
}
``````
原文作者：B树
原文地址: https://blog.csdn.net/bless924295/article/details/77150902
本文转自网络文章，转载此文章仅为分享知识，如有侵权，请联系博主进行删除。