atcoder-abc-070D
来源:互联网 发布:淘宝缩水女 编辑:程序博客网 时间:2024/06/05 07:59
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;
}
阅读全文
0 0
- atcoder-abc-070D
- AtCoder Beginner Contest 070 ABC C++&&python
- Atcoder ABC 061D Score Attack 最长路+判环
- AtCoder Beginner Contest 070-D
- Dijkstra算法 Atcoder-070-D
- AtCoder Beginner Contest 070 D
- Atcoder D
- atcoder 055D D
- atcoder square869120Contest #4 D
- Atcoder 2334 D
- Atcoder ARC 077 D
- AtCoder-RC078 D
- AtCoder 079D Decrease
- atcoder 062D
- Atcoder arc 084 D
- [atcoder] agc86 D
- AtCoder Beginner Contest 068 ABC C++&&python
- AtCoder Beginner Contest 069 ABC C++&&Python
- DozerBeanMapper简单封装, 实现深度转换Bean<->Bean的Mapper
- JMX简介及实践
- javah命令自动生成JNI头文件+Eclipse自动配置
- 《视频直播技术详解》系列:(2)架构
- [ACL2015]Improved Semantic Representations From Tree-Structured Long Short-Term Memory Networks
- atcoder-abc-070D
- AR导览智慧旅游解决方案-广东海狸信息科技
- 文本超出隐藏.......
- 深入理解Java之线程池
- JavaScript是如何实现继承的(六种方式)
- 时间的常见获取方法
- 指针学习
- JAVA 序列化存/读小例子
- Cocos项目为安卓添加获取手机信号强度和网络类型的功能(JAVA/C++/Lua)