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 (≤10^3) and Ne (≤10^5), 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.
思路
这是一个用dijkstra求解最短路径问题,不过有一点不一样。本题需要判断路径上的每个结点是不是当前距离最短的结点,可以在dijkstra里面判断min是不是等于s[i],也可以在所有的最短路径dis都求出来之后判断。相比较而言,前者简化了计算,更推荐使用!
代码
#include<stdio.h>
#include<algorithm>
using namespace std;
const int maxn=1005;
const int inf=100000000;
int nv,ne,k,g[maxn][maxn],s[maxn],dis[maxn];
bool vis[maxn];
void dijkstra(int x){
fill(dis,dis+maxn,inf);
fill(vis,vis+maxn,false);
dis[x]=0;
for(int i=1;i<=nv;i++){
int u=-1,min=inf;
for(int j=1;j<=nv;j++){
if(vis[j]==false&&dis[j]<min){
u=j;
min=dis[j];
}
}
if(u==-1) return;
vis[u]=true;
for(int v=1;v<=nv;v++){
if(vis[v]==false&&g[u][v]!=inf&&dis[v]>dis[u]+g[u][v]){
dis[v]=dis[u]+g[u][v];
}
}
}
}
int main(){
scanf("%d%d",&nv,&ne);
int a,b;
bool flag=true;
fill(g[0],g[0]+maxn*maxn,inf);
for(int i=0;i<ne;i++){
scanf("%d%d",&a,&b);
scanf("%d",&g[a][b]);
g[b][a]=g[a][b];
}
scanf("%d",&k);
for(int i=0;i<k;i++){
for(int j=0;j<nv;j++)
scanf("%d",&s[j]);
dijkstra(s[0]);
fill(vis,vis+maxn,false);
vis[s[0]]=true;
for(int j=1;j<nv;j++){
int min=inf;
for(int k=1;k<=nv;k++){
if(vis[k]==false&&dis[k]<min)
min=dis[k];
}
if(dis[s[j]]==min)
vis[s[j]]=true;
else{
flag=false;
break;
}
}
printf("%s\n",flag?"Yes":"No");
}
}