无法ac,不知道为啥。。。区别就是数组模拟了队列
#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;
}
别人的代码,可以ac。。。。不理解
#include <cstring>
#include <iostream>
#include <queue>
using namespace std;
const int N = 2e3 + 10, M = 1e4 + 10;
int n, m;
int head[N], e[M], ne[M], w[M], idx;
bool st[N];
int dist[N];
int cnt[N];
void add(int a, int b, int c)
{
e[idx] = b;
ne[idx] = head[a];
w[idx] = c;
head[a] = idx++;
}
bool spfa(){
queue<int> q;
for(int i=1;i<=n;i++){
q.push(i);
st[i]=true;
}
while(q.size()){
int t = q.front();
q.pop();
st[t]=false;
for(int i = head[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.push(j);
st[j]=true;
}
}
}
}
return false;
}
int main()
{
cin >> n >> m;
memset(head, -1, sizeof head);
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;
}
队列空间不够,spfa每个点可能多次入队,建议看看y总的循环队列
哇,感谢大佬啊