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 N
v (≤10 3) and N e(≤10 5 ), which are the total numbers of vertices and edges, respectively. Hence the vertices are numbered from 1 to N v.
Then N elines 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 N
v
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算法每次求得一条最短路之后,都会把终点t加入到集合st里面,然后对所有不在集合里的点修改其当前最短路径。因此只需要判断给的点是不是当前dijkstra选取的点,如果是,代表给的点是当前选取的最短路的终点,反知,不是
cpp代码
#include<iostream>
#include<cstring>
using namespace std;
int n,m;
const int N=1010;
int g[N][N];
bool st[N];
int dist[N];
int judeg[N];
bool dij(){
memset(dist,0x3f,sizeof dist);
memset(st,0,sizeof st);
dist[judeg[0]]=0;
for(int i=0;i<n;i++){
int t=-1;
for(int j=1;j<=n;j++){
if(!st[j]&&(!~t||dist[j]<dist[t]))t=j;
}
if(dist[t]<dist[judeg[i]])return false;
st[t]=true;
for(int j=1;j<=n;j++)
dist[j]=min(dist[j],dist[t]+g[t][j]);
}
return true;
}
int main(){
cin>>n>>m;
memset(g,0x3f,sizeof g);
for(int i=0;i<m;i++){
int a,b,c;
cin>>a>>b>>c;
g[a][b]=g[b][a]=min(g[a][b],c);
}
int q;
cin>>q;
while(q--){
for(int i=0;i<n;i++)cin>>judeg[i];
bool st=dij();
if(st)puts("Yes");
else puts("No");
}
return 0;
}