用自己写的队列(提交记录):
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e3+10,M=6e3+10;
int head[N],e_cnt=0;
struct EDGE{int to,pre,w;}e[M];
void add_edge(int from,int to,int w){
e[++e_cnt]=EDGE{to,head[from],w};
head[from]=e_cnt;
}
struct my_que{
int val[N],head=1,tail=1;
void push(int x){val[tail++]=x;}
void pop(){head++;}
int top(){return val[head];}
int size(){return tail-head;}
bool empty(){return tail-head==0;}
void clr(){head=1,tail=1,memset(val,0,sizeof(val));};
}que;
int T,n,m,dis[N],len[N];
bool book[N];
void init(){
for(int i=1;i<M;i++)e[i]=EDGE{0,0,0};
e_cnt=0;
memset(head,0,sizeof(head));
memset(dis,0x3f,sizeof(dis));
memset(len,0,sizeof(len));
memset(book,0,sizeof(book));
que.clr();
}
bool spfa(){
que.push(1),dis[1]=0,book[1]=1;
while(!que.empty()){
int u=que.top();
que.pop();
book[u]=0;
for(int i=head[u];i;i=e[i].pre){
int v=e[i].to,w=e[i].w;
if(dis[v]>dis[u]+w){
dis[v]=dis[u]+w;
len[v]=len[u]+1;
if(len[v]>=n)return true;
if(!book[v])que.push(v),book[v]=1;
}
}
}
return false;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>T;
while(T--){
init();
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v,w;
cin>>u>>v>>w;
add_edge(u,v,w);
if(w>=0) add_edge(v,u,w);
}
if(spfa())cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}
然后把自己写的换成 STL 的 queue 就能过
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N=2e3+10,M=6e3+10;
int head[N],e_cnt=0;
struct EDGE{int to,pre,w;}e[M];
void add_edge(int from,int to,int w){
e[++e_cnt]=EDGE{to,head[from],w};
head[from]=e_cnt;
}
queue<int>que;
int T,n,m,dis[N],len[N];
bool book[N];
void init(){
for(int i=1;i<M;i++)e[i].pre=0;;
e_cnt=0;
memset(head,0,sizeof(head));
memset(dis,0x3f,sizeof(dis));
memset(len,0,sizeof(len));
memset(book,0,sizeof(book));
}
bool spfa(){
que.push(1),dis[1]=0,book[1]=1;
while(!que.empty()){
int u=que.front();
que.pop();
book[u]=0;
for(int i=head[u];i;i=e[i].pre){
int v=e[i].to,w=e[i].w;
if(dis[v]>dis[u]+w){
dis[v]=dis[u]+w;
len[v]=len[u]+1;
if(len[v]>=n)return true;
if(!book[v])que.push(v),book[v]=1;
}
}
}
return false;
}
int main(){
ios::sync_with_stdio(false);
cin.tie(0),cout.tie(0);
cin>>T;
while(T--){
init();
cin>>n>>m;
for(int i=1;i<=m;i++){
int u,v,w;
cin>>u>>v>>w;
add_edge(u,v,w);
if(w>=0) add_edge(v,u,w);
}
if(spfa())cout<<"YES\n";
else cout<<"NO\n";
}
return 0;
}