1163 Dijkstra Sequence (30 分)
Dijkstra Sequence
题目描述:
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 (≤103) and N**e (≤105), which are the total numbers of vertices and edges, respectively. Hence the vertices are numbered from 1 to N**v.
Then N**e 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 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
思路:
题目大意是问下面给出的序列符不符合狄杰斯特拉序列,用狄杰斯特拉算法去做就行。
代码:
#include "iostream"
#include "string.h"
using namespace std;
#define Inf 0x3f3f3f
#define size 1002
int dis[size][size];
int ans[size];
int m,n,k;
bool check(){
int used[size] = {0},dist[size] = {0};
memset(dist,0x3f,sizeof (dist));
dist[ans[1]] = 0;
for (int i=1;i<=m;i++){
int u = -1;
// 先找到最小值
for(int j=1; j<= m;j++){
if( !used[j] && (u==-1 || dist[u] > dist[j]) ) u = j;
}
if (dist[u] != dist[ans[i]]){
return false;
}
for(int j=1; j<=m; j++){
if (j == u) continue;
dist[j] = min(dist[j], dist[u] + dis[u][j]);
}
used[u] = 1;
}
return true;
}
int main(){
cin >>m>>n;
int a,b,c;
memset(dis,Inf, sizeof(dis));
while(n--){
cin >>a>>b>>c;
dis[a][b] = dis[b][a] = c;
}
cin >>k;
while(k--){
for(int i=1;i<=m;i++){
cin >>ans[i];
}
if (check()){
cout <<"Yes"<<endl;
}else{
cout <<"No" <<endl;
}
}
return 0;
}
本博客所有文章除特别声明外,均采用 CC BY-SA 4.0 协议 ,转载请注明出处!