Time limit : 2sec / Memory limit : 256MB
Score : 400 points
Problem Statement
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
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
Output
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.
Sample Input 1
题意:
一颗无向树,有n-1条边,求x经过k到达y的最短路径
思路:
转换成从k点到x和y两点的最短路径
注意:
不能用邻接矩阵储存树,数据量过大,要用邻接表;
树为无向树;
#include <iostream>
#include <cstdio>#include <vector>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
const int N=1e5+50;
const long long INF=1e18;
int n;
int k,p;
long long dis[N];
int vis[N];
struct Edge
{
int y;
int w;
};
vector<Edge> v[N];
void Init()
{
for(int i=0; i<=n; i++)
v[i].clear();
}
void spfa(int s)
{
queue<int> p;
p.push(s);
for(int i=0; i<=n; i++) dis[i]=INF;
dis[s]=0;
memset(vis,0,sizeof(vis));
vis[s]=1;
while(!p.empty())
{
int u=p.front();
p.pop();
vis[u]=0;
for(int i=0; i<v[u].size(); i++)
{
int w=v[u][i].w;
int y=v[u][i].y;
if(dis[y]>dis[u]+w)
{
dis[y]=dis[u]+w;
if(!vis[y])
{
p.push(y);
vis[y]=1;
}
}
}
}
}
int main()
{
scanf("%d",&n);
Init();
for(int i=0; i<n-1; i++)
{
int x,y,w;
scanf("%d%d%d",&x,&y,&w);
Edge now;
now.y=y;
now.w=w;
v[x].push_back(now);
now.y=x;
v[y].push_back(now);
}
scanf("%d%d",&p,&k);
spfa(k);
for(int i=0; i<p; i++)
{
int x,y;
scanf("%d%d",&x,&y);
cout<<dis[x]+dis[y]<<endl;
}
return 0;
}