bzoj 1602: [Usaco2008 Oct]牧场行走【瞎搞】

时间:2023-03-09 15:10:59
bzoj 1602: [Usaco2008 Oct]牧场行走【瞎搞】

本来想爆手速写个树剖,然而快下课了就手残写了了个n方的短小……

暴力把查询的两个点中深的一个跳上来,加上边权,然后一起跳加边权就行了

#include<iostream>
#include<cstdio>
using namespace std;
const int N=1005;
int n,q,h[N],cnt,fa[N],va[N],de[N];
struct qwe
{
int ne,to,va;
}e[N<<1];
int read()
{
int r=0,f=1;
char p=getchar();
while(p>'9'||p<'0')
{
if(p=='-')
f=-1;
p=getchar();
}
while(p>='0'&&p<='9')
{
r=r*10+p-48;
p=getchar();
}
return r*f;
}
void add(int u,int v,int w)
{
cnt++;
e[cnt].ne=h[u];
e[cnt].to=v;
e[cnt].va=w;
h[u]=cnt;
}
void dfs(int u,int fat)
{
fa[u]=fat;
de[u]=de[fat]+1;
for(int i=h[u];i;i=e[i].ne)
if(e[i].to!=fat)
{
va[e[i].to]=e[i].va;
dfs(e[i].to,u);
}
}
int main()
{
n=read(),q=read();
for(int i=1;i<n;i++)
{
int x=read(),y=read(),z=read();
add(x,y,z),add(y,x,z);
}
dfs(1,0);
while(q--)
{
int x=read(),y=read(),ans=0;
if(de[x]<de[y])
swap(x,y);
while(de[x]>de[y])
ans+=va[x],x=fa[x];
while(x!=y)
ans+=va[x]+va[y],x=fa[x],y=fa[y];
printf("%d\n",ans);
}
return 0;
}