Transit Tree Path 建树求最短距离
问题 D: Transit Tree Path
时间限制: 1 Sec 内存限制: 128 MB
提交: 243 解决: 76
[提交] [状态] [讨论版] [命题人:admin]
题目描述
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N−1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N−1) connects Vertices ai and bi, and has a length of ci.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
find the length of the shortest path from Vertex xj and Vertex yj via Vertex K.
Constraints
3≤N≤105
1≤ai,bi≤N(1≤i≤N−1)
1≤ci≤109(1≤i≤N−1)
The given graph is a tree.
1≤Q≤105
1≤K≤N
1≤xj,yj≤N(1≤j≤Q)
xj≠yj(1≤j≤Q)
xj≠K,yj≠K(1≤j≤Q)
输入
Input is given from Standard Input in the following format:
N
a1 b1 c1
:
aN−1 bN−1 cN−1
Q K
x1 y1
:
xQ yQ
输出
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
样例输入
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
样例输出
3
2
4
提示
The shortest paths for the three queries are as follows:
Query 1: Vertex 2 → Vertex 1 → Vertex 2 → Vertex 4 : Length 1+1+1=3
Query 2: Vertex 2 → Vertex 1 → Vertex 3 : Length 1+1=2
Query 3: Vertex 4 → Vertex 2 → Vertex 1 → Vertex 3 → Vertex 5 : Length 1+1+1+1=4
给一颗树及距离,寻找经过k的路径的最短长度
以k为根建立树,用dfs
找了很长时间bug,才发现输入的数据是n-1组,不是n组
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxx=1e5+100;
const int INF=99999999;
const int MOD=1e9+7;
typedef long long ll;
int n;
struct node
{
int r,nextt;
ll dis;
}s[maxx*2];
ll d[maxx];
int h[maxx];
int cnt;
void add(int a,int b,ll c)
{
s[cnt].r=b;
s[cnt].dis=c;
s[cnt].nextt=h[a];
h[a]=cnt;
cnt++;
}
void dfs(int k,int dd)
{
for(int i=h[k]; i!=-1; i=s[i].nextt){
int v=s[i].r;
if(v==dd) continue;
d[v]=d[k]+s[i].dis;
dfs(v,k);
}
}
int main()
{
scanf("%d",&n);
int a,b;
ll c;
cnt=0;
memset(h,-1,sizeof(h));
memset(d,0,sizeof(d));
for(int i=0; i<n-1; i++){
scanf("%d%d%lld",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
int m,k;
scanf("%d%d",&m,&k);
dfs(k,-1);
while(m--){
scanf("%d%d",&a,&b);
printf("%lld\n",d[a]+d[b]);
}
return 0;
}