LCA入门问题,以后总结~~~
#include<algorithm>
#include<iostream>
#include<cstring>
#include<cstdio>
#include<string>
#include<string>
#include<vector>
#include<queue>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define rep(i,a,n) for (int i=a;i<n;i++)
#define per(i,a,n) for (int i=n-1;i>=a;i--)
#define oo cout<<"!!!"<<endl;
typedef long long ll;
typedef unsigned long long ull;
#define ms(s) memset(s, 0, sizeof(s))
const int inf = 0x3f3f3f3f;
//head
const int maxn = 5e4+11;
int f[maxn][20],d[maxn],dist[maxn];
int ver[maxn*2],Next[maxn*2],edge[maxn*2],head[maxn],tot;
int t;
void add(int x,int y ,int z)
{
ver[++tot] = y;edge[tot] = z;Next[tot] = head[x];head[x] = tot;
}
void bfs()
{
queue<int>q;
q.push(1);
d[1] = 1;
while(!q.empty())
{
int x = q.front();q.pop();
for(int i = head[x];i;i = Next[i])
{
int y = ver[i];
if(d[y])continue;
d[y] = d[x] + 1;
dist[y] = dist[x] + edge[i];
f[y][0] = x;
for(int j = 1;j<=t;j++)
f[y][j] = f[f[y][j-1]][j-1];
q.push(y);
}
}
}
int lca(int x,int y)
{
if(d[x]>d[y])swap(x,y);
for(int i = t;i>=0;i--) if(d[f[y][i]] >= d[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 main()
{
int T;cin>>T;
while(T--)
{
int n,m;
cin>>n>>m;
t = (int)(log(n)/log(2))+1;
rep(i,1,n+1)head[i] = d[i] = dist[t] = 0;
tot = 0;
rep(i,1,n)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);add(y,x,z);
}
bfs();
rep(i,1,m+1)
{
int x,y;
scanf("%d%d",&x,&y);
printf("%d\n",dist[x]+dist[y]-2*dist[lca(x,y)]);
}
}
}