spfa什么玩意,我的为啥用数组模拟队列就段错误。。垃圾
作者:
VALUE_5
,
2021-11-15 12:42:59
,
所有人可见
,
阅读 207
#include<bits/stdc++.h>
using namespace std;
const int N = 100010;
int h[N], e[N],ne[N],w[N],idx;
int dist[N],cnt[N];
int q[N];
bool st[N];
int n,m;
void add(int a, int b, int c){
e[idx] = b;
ne[idx] = h[a];
w[idx] = c;
h[a] = idx++;
}
bool spfa(){
int hh = 0, tt = -1;
for(int i = 1; i <= n; i++){
q[++tt] = i;
st[i] = true;
}
while(hh <= tt){
int t = q[hh++];
st[t] = false;
for(int i = h[t]; i != -1; i =ne[i]){
int j = e[i];
if(dist[j] > dist[t] + w[i]){
dist[j] = dist[t] + w[i];
cnt[j] = cnt[t] + 1;
if(cnt[j] >= n){
return true;
}
if(!st[j]){
q[++tt] = j;
st[j] = true;
}
}
}
}
return false;
}
int main(){
cin >> n >> m;
memset(h, -1, sizeof h);
for(int i = 0; i < m; i++){
int a, b, c;
cin >> a >> b >> c;
add(a, b, c);
}
if(spfa()){
cout << "Yes" << endl;
}else{
cout << "No" << endl;
}
return 0;
}