用spfa 判负环
#include<stdio.h>
#include<cstring>
#include<queue>
#include<algorithm>
using namespace std;
struct my{
int v;
int next;
int dist;
};
int m,n;
const int maxn=100000;
my bian[maxn];
int adj[maxn];
int fa;
bool vis[maxn];
int d[maxn];
int cnt[maxn];
void myinsert(int u,int v,int zhi){
bian[++fa].v=v;
bian[fa].dist=zhi;
bian[fa].next=adj[u];
adj[u]=fa;
}
bool spfa(){
queue<int>q;
for (int i=1;i<=n;i++){
q.push(i);
d[i]=0;
}
vis[1]=true;
while(!q.empty()){
int u=q.front();
q.pop();
vis[u]=false;
for (int i=adj[u];i!=-1;i=bian[i].next){
if(d[bian[i].v]>d[u]+bian[i].dist){
d[bian[i].v]=d[u]+bian[i].dist;
if(!vis[bian[i].v]){
q.push(bian[i].v);
vis[bian[i].v]=true;
if(++cnt[bian[i].v]>n) return true;
}
}
}
}
return false;
}
int main(){
memset(bian,-1,sizeof(bian));
memset(adj,-1,sizeof(adj));
scanf("%d%d",&n,&m);
int u,v,zhi;
for (int i=1;i<=m;i++){
scanf("%d%d%d",&u,&v,&zhi);
myinsert(u,v,zhi);
myinsert(v,u,zhi);
}
if( spfa()) printf("yes\n");
else printf("no\n");
return 0;
}