负环
做一次最短路,并且记录最短路径中通过的边数,若边数 则最短路中出现环,即出现负环。最长路正环同理。
#include<bits/stdc++.h>
#define ll long long
#define db double
#define filein(a) freopen(#a".in","r",stdin)
#define fileot(a) freopen(#a".out","w",stdout)
#define sky fflush(stdout);
#define gc getchar
#define pc putchar
namespace IO{
inline bool blank(const char &c){
return c==' ' or c=='\n' or c=='\t' or c=='\r' or c==EOF;
}
inline void gs(char *s){
char ch=gc();
while(blank(ch) ) {ch=gc();}
while(!blank(ch) ) {*s++=ch;ch=gc();}
*s=0;
}
inline void gs(std::string &s){
char ch=gc();s+='#';
while(blank(ch) ) {ch=gc();}
while(!blank(ch) ) {s+=ch;ch=gc();}
}
inline void ps(char *s){
while(*s!=0) pc(*s++);
}
inline void ps(const std::string &s){
for(auto it:s)
if(it!='#') pc(it);
}
template<class T>
inline void read(T &s){
s=0;char ch=gc();bool f=0;
while(ch<'0'||'9'<ch) {if(ch=='-') f=1;ch=gc();}
while('0'<=ch&&ch<='9') {s=s*10+(ch^48);ch=gc();}
if(ch=='.'){
db p=0.1;ch=gc();
while('0'<=ch&&ch<='9') {s=s+p*(ch^48);p*=0.1;ch=gc();}
}
s=f?-s:s;
}
template<class T,class ...A>
inline void read(T &s,A &...a){
read(s);read(a...);
}
};
using IO::read;
using IO::gs;
using IO::ps;
const int N=2e3+3;
const int M=6e3+3;
const int inf=1e9;
int n,m;
int head[N],nxt[M];
struct node{
int u,v,w;
}to[M];
int Etot=-1;
inline void link(int u,int v,int w){
nxt[++Etot]=head[u];
head[u]=Etot;
to[Etot]={u,v,w};
}
inline void link1(int u,int v,int w){
link(u,v,w);link(v,u,w);
}
int dis[N],cnt[N];
bool inq[N];
inline bool spfa(){
static std::queue<int>q;
while(!q.empty() ) q.pop();
for(int i=1;i<=n;++i){
dis[i]=inf;
inq[i]=cnt[i]=0;
}
cnt[1]=0;dis[1]=0;inq[1]=1;
q.push(1);
while(!q.empty() ){
int u=q.front();q.pop();
inq[u]=0;
for(int i=head[u];~i;i=nxt[i]){
int v=to[i].v,w=to[i].w;
if(dis[v]>dis[u]+w){
dis[v]=dis[u]+w;
cnt[v]=cnt[u]+1;
if(cnt[v]>=n) return 1;
if(!inq[v]){
q.push(v);
}
}
}
}
return 0;
}
int main(){
filein(a);fileot(a);
int T;read(T);
while(T--){
read(n,m);
Etot=-1;
memset(head,-1,sizeof(head) );
for(int i=1;i<=m;++i){
int u,v,w;
read(u,v,w);
if(w>=0){
link1(u,v,w);
}else{
link(u,v,w);
}
}
if(spfa() )printf("YES\n");
else printf("NO\n");
}
return 0;
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具