How far away hdu 2586

#define  _CRT_SECURE_NO_WARNINGS


#include<iostream>
#include<iomanip>
#include<vector>
#include<string>
#include<cstring>
using namespace std;
#define N  50000
int a[N], vis[N], dist[N];
int n, m, t;
int x[N], y[N], z[N];
struct node
{
int next;
int to;
int w;
};
node s[3 * N]; int head[N];
void addeadge(int x, int y, int z)
{
s[t].to = y;
s[t].w = z;
s[t].next = head[x];
head[x] = t; t++;
s[t].to = x;
s[t].w = z;
s[t].next = head[y];
head[y] = t;
t++;




}
int find(int x)
{
return a[x] == x ? x : a[x] = find(a[x]);
}
void LCA(int i)
{
vis[i] = 1;
a[i] = i;
int k;

//cout << i << endl;
/*for (int j = 0; j<m; j++)
{


//cout << i << " " << x[j] << " " << y[j] << vis[y[j]] <<" "<< vis[x[j]] << endl;
if (x[j] == i && vis[y[j]] == 1)
{
z[j] = find(y[j]);
}
if (y[j] == i && vis[x[j]] == 1)
{
z[j] = find(x[j]);
}


}*/

for (int j = head[i]; j != -1; j = s[j].next)
{
k = s[j].to;
if (vis[k] == 1)continue;
//cout << i << " " << k << endl;
dist[k] = dist[i] + s[j].w;
LCA(k);
a[k] = i;


}
for (int j = 0; j<m; j++)
{


//cout << i << " " << x[j] << " " << y[j] << vis[y[j]] <<" "<< vis[x[j]] << endl;
if (x[j] == i && vis[y[j]] == 1)
{
z[j] = find(y[j]);
}
if (y[j] == i && vis[x[j]] == 1)
{
z[j] = find(x[j]);
}


}




}
int  main()
{
int  xx, yy, k, zz;
int T;
cin >> T;
while (T--)
{
cin >> n >> m;
memset(head, -1, sizeof(head));
memset(vis, 0, sizeof(vis));
memset(dist, 0, sizeof(0));
t = 0;
for (int i = 1; i<n; i++)
{
cin >> xx >> yy >> zz;
addeadge(xx, yy, zz);
}
for (int j = 0; j<m; j++)
{


cin >> x[j] >> y[j];
}
LCA(1);
for (int i = 0; i < m; i++)
{
//cout << x[i] << y[i] << z[i] << endl;
cout << dist[x[i]] + dist[y[i]] - 2 * dist[z[i]] << endl;
}
}
return 0;

}

/*自己写这个的时候  犯了比较严重的错误  自己的竟然把LCA和输入数据写反了 害我找了很长时间的错误  下次 注意    还有那个判断最近祖先的循环可以放到前面或者后面 都没有问题*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值