题目描述
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
这道题的主要思路就是用dfs求出各点到必经点k的距离,然后最后的结果就是必经点到出发点的距离加上必经点到结束点的距离
下面是代码:
#include<iostream>
#include<vector>
using namespace std;
#define MAX_N 100001
typedef long long int LL;
vector<pair<int, int> > adj[MAX_N];
LL dis[MAX_N];//这个数组就是用来存放各点到必经点的距离,注意类型一定要用long long,否者结果会出错
bool vis[MAX_N];
void dfs(int v)
{
vis[v] = true;
for (LL i = 0; i < adj[v].size(); i++) {
LL u = adj[v][i].first;
LL w = adj[v][i].second;
if (!vis[u]) {
dis[u] = dis[v] + w;
dfs(u);
}
}
}
int main(void)
{
ios::sync_with_stdio(false);//如果用cin读取大量数据,加上此举可以减少读取时间
int n, k, q;
cin>>n;
for (LL i = 1; i < n; i++) {
int a, b, c;
cin>>a>>b>>c;
adj[a].push_back(make_pair(b, c));
adj[b].push_back(make_pair(a, c));
}
cin>>q>>k;
dfs(k);
while (q--) {
int x, y;
cin>>x>>y;
printf("%lld\n",(dis[x] + dis[y]));/*这一句不要用cout输出,如果换成c
out的话会超时(cout比printf的效率低,当时就
是把原来的cout改成print,然后题目直接从超时变ac,有
兴趣的朋友可以找一个oj试一下)*/
}
return 0;
}