这个题目一定要理解题意,{ 5, 1, 3, 4, 2 } and { 5, 3, 1, 2, 4 } 明显在说不是要求图遍历的路径,如果使用 pre[maxn] 记录路径,就错了。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int const maxn = 1010, inf = 1000000000;
int G[maxn][maxn], d[maxn], nv, ne, k, st, ed, flag = 0;
bool vis[maxn];
vector<int> path;
bool dijkstra(int s){
fill(d, d + maxn, inf);
fill(vis, vis + maxn, 0);
d[s] = 0;
for(int i = 0; i < nv; i++){
int MIN = inf, u = -1;
for(int j = 1; j <= nv; j++){
if(vis[j] == false && d[j] < MIN){
u = j; MIN = d[j];
}
}
if(u == -1 || d[u] != d[path[i]]) return false;
vis[u] = true;
for(int v = 1; v <= nv; v++){
if(vis[v] == false && G[u][v] != inf){
if(d[u] + G[u][v] < d[v]){
d[v] = d[u] + G[u][v];
}
}
}
}
return true;
}
int main(){
cin >> nv >> ne;
fill(G[0], G[0] + maxn*maxn, inf);
for(int i = 1; i <= ne; i++){
int a, b, w;
cin >> a >> b >> w;
G[a][b] = G[b][a] = w;
}
cin >> k;
for(int i = 0; i < k; i++){
path.clear();
for(int j = 0; j < nv; j++){
int a;
cin >> a; path.push_back(a);
}
st = path[0];
if(dijkstra(st)) printf("Yes\n");
else printf("No\n");
}
return 0;
}
来源:CSDN
作者:J_北冥有鱼
链接:https://blog.csdn.net/weixin_35737222/article/details/104226185