# AtCoder Beginner Contest 133 F - Colorful Tree

```#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
int n,m,t;
typedef long long LL;
struct query{
int x,y,u,v;
long long ans;
}Q[N];
vector<int> v[N],b[N];

void add_edge(int x,int y,int c,int d) {
}

int dep[N],f[N][20];
void dfs1(int x,int fa,int d) {
dep[x]=d;
int y=to[i];
if (y==fa) continue;
f[y][0]=x;
for (int j=1;j<=t;j++) f[y][j]=f[f[y][j-1]][j-1];
dfs1(y,x,d+1);
}
}

int LCA(int x,int y) {
if (dep[x]>dep[y]) swap(x,y);
for (int i=t;i>=0;i--)
if (dep[f[y][i]]>=dep[x]) y=f[y][i];
if (x==y) return x;
for (int i=t;i>=0;i--)
if (f[x][i]!=f[y][i]) x=f[x][i],y=f[y][i];
return f[x][0];
}

int sumc[N],sumd[N];
void dfs2(int x,int fa,int dis) {
for (int i=0;i<v[x].size();i++) {
int id=v[x][i];
Q[id].ans+=(LL)dis*b[x][i];
Q[id].ans-=(LL)sumd[Q[id].x]*b[x][i];
Q[id].ans+=(LL)sumc[Q[id].x]*Q[id].y*b[x][i];
}
int y=to[i];
if (y==fa) continue;
sumc[col[i]]++;
sumd[col[i]]+=len[i];
dfs2(y,x,dis+len[i]);
sumc[col[i]]--;
sumd[col[i]]-=len[i];
}
}

int main()
{
cin>>n>>m;
t=log2(n)+1;
for (int i=1;i<n;i++) {
int x,y,c,d;
scanf("%d%d%d%d",&x,&y,&c,&d);
}
dfs1(1,0,1);
for (int i=1;i<=m;i++) {
scanf("%d%d%d%d",&Q[i].x,&Q[i].y,&Q[i].u,&Q[i].v);
v[Q[i].u].push_back(i); b[Q[i].u].push_back(1);
v[Q[i].v].push_back(i); b[Q[i].v].push_back(1);
int lca=LCA(Q[i].u,Q[i].v);
v[lca].push_back(i); b[lca].push_back(-2);
}
dfs2(1,0,0);
for (int i=1;i<=m;i++) printf("%lld\n",Q[i].ans);
return 0;
} ```

AtCoder Beginner Contest 133 F - Colorful Tree

(0)
(0)