2018年第三阶段个人训练赛第四场6690 Problem D Transit Tree Path

题目描述

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

题意:已知一棵无向树有n个点,n-1条边,现给你m个问题和一个点k,每个问题包括两个点x和y,问从结点x到结点y经过结点k的最短路径。

思路:因为是树,所以每个点都连通。结点xy通过结点k的最短路径可以分成两部分:结点kx的最短路径和结点ky的最短路径。如此,通过一个简单的DFS,求解结点ki(1≤i≤n)的路径长度dis[i]。则查询的返回值为dis[x]+dis[y]

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<vector>
using namespace std;
vector<pair<int ,int> >a[200005];
int vis[100005]={0};
long long int dis[100005]={0};
void dfs(int k)
{
   vis[k]=1;
   for(int i=0;i<a[k].size();i++)
   {
      int fir=a[k][i].first;
      int sec=a[k][i].second;
      if(vis[fir])
        continue;
      dis[fir]=dis[k]+sec;
      dfs(fir);
   }
}
int main()
{
   int i,j,n;
   scanf("%d",&n);
   for(i=1;i<n;i++)
   {
      int u,v;
      long long int w;
      scanf("%d%d%lld",&u,&v,&w);
      a[u].push_back(make_pair(v,w));
      a[v].push_back(make_pair(u,w));
   }
   int m,k;
   scanf("%d%d",&m,&k);
   dfs(k);
   for(i=0;i<m;i++)
   {
      int x,y;
      scanf("%d%d",&x,&y);
      printf("%lld\n",dis[x]+dis[y]);
   }
   return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值