题目链接:点击打开链接
题解思路:dfs一下记住父节点然后持续往上搜,知道两点相同,速度也挺快的
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mx = 1e5+10;
int n,m,val[mx],head[mx],tot,fa[mx],deep[mx];
ll ans[mx];
struct node{
int y,nxt;
}Edge[mx<<1];
void AddEdge(int x,int y){
Edge[tot].y = y;
Edge[tot].nxt = head[x];
head[x] = tot++;
}
void dfs(int x,int f){
for(int i=head[x];i!=-1;i=Edge[i].nxt){
int son = Edge[i].y;
if(son==f) continue;
fa[son] = x;
deep[son] = deep[x] + 1;
dfs(son,x);
}
}
int main(){
while(~scanf("%d%d",&n,&m)){
memset(head,-1,sizeof(head));
for(int i=1;i<=n;i++) scanf("%d",val+i);
int a,b,c,d;
deep[0] = tot = 0;
for(int i=1;i<n;i++){
scanf("%d%d",&a,&b);
AddEdge(a,b);
AddEdge(b,a);
}
dfs(1,0);
int cnt = 1;
while(m--){
scanf("%d%d%d%d",&a,&b,&c,&d);
if(deep[a]<deep[b]) swap(a,b);
ll ret = 0;
while(deep[a]!=deep[b]){
if(val[a]>=c&&val[a]<=d) ret += val[a];
a = fa[a];
}
while(a!=b){
if(val[a]>=c&&val[a]<=d) ret += val[a];
if(val[b]>=c&&val[b]<=d) ret += val[b];
a = fa[a];
b = fa[b];
}
if(val[a]>=c&&val[a]<=d) ret += val[a];
ans[cnt++] = ret;
}
for(int i=1;i<cnt-1;i++) printf("%lld ",ans[i]);
printf("%lld\n",ans[cnt-1]);
}
return 0;
}