1163 Dijkstra Sequence – PAT甲级真题

Dijkstra’s algorithm is one of the very famous greedy algorithms.
It is used for solving the single source shortest path problem which gives the shortest paths from one particular source vertex to all the other vertices of the given graph. It was conceived by computer scientist Edsger W. Dijkstra in 1956 and published three years later.

In this algorithm, a set contains vertices included in shortest path tree is maintained. During each step, we find one vertex which is not yet included and has a minimum distance from the source, and collect it into the set. Hence step by step an ordered sequence of vertices, let’s call it Dijkstra sequence, is generated by Dijkstra’s algorithm.

On the other hand, for a given graph, there could be more than one Dijkstra sequence. For example, both { 5, 1, 3, 4, 2 } and { 5, 3, 1, 2, 4 } are Dijkstra sequences for the graph, where 5 is the source. Your job is to check whether a given sequence is Dijkstra sequence or not.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive integers Nv​ (≤103) and Ne​ (≤105), which are the total numbers of vertices and edges, respectively. Hence the vertices are numbered from 1 to Nv​.

Then Ne​ lines follow, each describes an edge by giving the indices of the vertices at the two ends, followed by a positive integer weight (≤100) of the edge. It is guaranteed that the given graph is connected.

Finally the number of queries, K, is given as a positive integer no larger than 100, followed by K lines of sequences, each contains a permutationof the Nv​ vertices. It is assumed that the first vertex is the source for each sequence.

All the inputs in a line are separated by a space.

Output Specification:

For each of the K sequences, print in a line Yes if it is a Dijkstra sequence, or No if not.

Sample Input:

5 7
1 2 2
1 5 1
2 3 1
2 4 1
2 5 2
3 5 1
3 4 1
4
5 1 3 4 2
5 3 1 2 4
2 3 4 5 1
3 2 1 5 4

Sample Output:

Yes
Yes
Yes
No

题目大意:Dijkstra算法用来解决单源最短路径问题,用来寻找从一个特定源顶点到给定图的所有其他顶点的最短路径。在每一步中,我们找到一个尚未包含且与源顶点距离最小的顶点,并将其收集到集合中。通过Dijkstra算法逐步生成的一个有序的序列称之为Dijkstra序列。对于给定的图,可能有多个Dijkstra序列。你的工作是检查给定的序列是否是Dijkstra序列。输入样例:第一行输入两个正整数Nv和Ne,分别是顶点和边的总数量。顶点的编号是1到Nv,然后是Ne行,每行通过给出两端顶点的编号来描述一条边,外加一个正整数,表示边的权重。保证给定的图是连通的。最后,给出一个正整数K表示查询的次数,然后是K行序列,每行包含Nv个顶点的排列,假设第一个顶点是每个序列的源点。一行中的所有输入由空格分隔。输出格式:对于K个序列中的每一个,如果它是Dijkstra序列,则输出一行Yes,否则输出No。
分析:V和E表示顶点和边的数量,二维数组Edge中存储两点之间的距离,数组Path为当前需要判断的序列,数组Distance为Dijskra最短路径起点到各个点的最短距离,flag记录当前路径是否为真,book标记确定好最短距离的点。直接丢到Dijskra算法里,判断每一步能不能由给定的路径完成,最后根据flag的值输出Yes或No~ 

 

❤ 点击这里 -> 订阅《PAT | 蓝桥 | LeetCode学习路径 & 刷题经验》by 柳婼

❤ 点击这里 -> 订阅《从放弃C语言到使用C++刷算法的简明教程》by 柳婼

❤ 点击这里 -> 订阅PAT甲级乙级、蓝桥杯、GPLT天梯赛、LeetCode题解离线版