模板SPFA判负环
Posted ieqefcr
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了模板SPFA判负环相关的知识,希望对你有一定的参考价值。
#include<bits/stdc++.h>
#pragma GCC optimize(3)
#define maxn 10000
#define maxm 10000
#define inf 2147483647
using namespace std;
int m, n;
int num = 0;
struct eg
{
int to;
int cost;
int next;
};
eg side[maxm];
int head[maxn], cnt[maxn], dis[maxn];
bool vis[maxn], flag = 0;
void addeg(int f, int t, int cost)
{
side[++num].next = head[f];
side[num].to = t;
side[num].cost = cost;
head[f] = num;
}
void spfa(int g)
{
dis[g] = 0;
vis[g] = 1;
queue<int>q;
q.push(g);
int x;
while(!q.empty())
{
x = q.front();
q.pop();
vis[x] = 0;
for(int i = head[x]; i != 0; i = side[i].next)
{
if(dis[x] + side[i].cost < dis[side[i].to])
{
dis[side[i].to] = dis[x] + side[i].cost;
cnt[side[i].to] = cnt[x] + 1;
if(cnt[side[i].to] >= n)
{
flag = 1;
return ;
}
if(!vis[side[i].to])
{
q.push(side[i].to);
vis[side[i].to] = 1;
}
}
}
}
return ;
}
int main()
{
int T;
int f, t, cost;
scanf("%d", &T);
while(T--)
{
num = 0;
scanf("%d%d", &n, &m);
// for(int i = 1; i <= m; i++)
// side[i].to = 0, side[i].next = 0, side[i].cost = 0;
for(int i = 0; i <= n; i++)
dis[i] = 0, cnt[i] = 0, vis[i] = 0, head[i] = 0, dis[i] = 0;
for(int i = 1; i <= m; i++)
{
scanf("%d%d%d", &f, &t, &cost);
if(cost < 0)
{
addeg(f, t, cost);
}
else
{
addeg(f, t, cost);
addeg(t, f, cost);
}
}
flag = 0;
for(int i = 1; i <= n; i++)
{
spfa(i);
if(flag)break;
}
if(flag) puts("YE5");
else puts("N0");
}
}
以上是关于模板SPFA判负环的主要内容,如果未能解决你的问题,请参考以下文章
poj3259 Wormholes (判负环)spfa(模板)