Transit Tree Path
时间限制: 1 Sec 内存限制: 128 MB
提交: 459 解决: 123
[提交] [状态] [讨论版] [命题人: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
题意,;
一个无向图,树形的,n个点,n-1条边,问两点间最短路,但要经过一个k点,也就是经过k点的最短路;
其实就是算出每个点到k点的最短路,把这两个点到k的最短距离加起来就是经过k点的两点间的最短距离了
求一个点到其他任一点的最短距离用队列优化的dijkstra,即可,这里使用学长的板子,还是很强的
代码
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <math.h>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <map>
using namespace std;
const int MAX_NUM = 0x3f3f3f3f;
const int N = 100005; ///点的最大值
const int M = 100005;///边的最大值
struct Edge
{
long long val;
int to;
Edge(int a=0,long long b=0):to(a),val(b) {}
bool operator <(const Edge &a) const
{
if(val == a.val) return to<a.to;
return val>a.val;
}
};
vector<Edge>ma[N];
bool vis[N];
long long dist[N];
int n,m;
void dijkstra(int start)
{
memset(vis,false,sizeof(vis));
memset(dist,0x3f,sizeof(dist));
priority_queue<Edge>que;
dist[start]=0;
vis[start]=true;
que.push(Edge(start,0));
while(!que.empty())
{
Edge fr = que.top();
que.pop();
for(int i=0; i<ma[fr.to].size(); i++)
{
Edge tmp = ma[fr.to][i];
if(dist[tmp.to] > fr.val + tmp.val)
{
dist[tmp.to] = fr.val + tmp.val;
que.push(Edge(tmp.to,dist[tmp.to]));
}
}
}
}
int main()
{
while(~scanf("%d",&n))
{
for(int i=0; i<=n; i++) ma[i].clear();
int from,to;
long long val;
for(int i=0; i<n-1; i++)
{
scanf("%d%d%lld",&from,&to,&val);
ma[from].push_back(Edge(to,val));
ma[to].push_back(Edge(from,val));
}
int q,k;
scanf("%d%d",&q,&k);
dijkstra(k);
int w,e;
for(int i=0; i<q; i++)
{
scanf("%d%d",&w,&e);
long long jj=dist[w]+dist[e];
printf("%lld\n",jj);
}
}
}