http://poj.org/problem?id=3259
第一周的题,已经是第二周末了。。还没做完。。唉。。效率啊。。。就是一个简单的判断有无负权值的环。
bellmen_ford做法
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include <iostream>
#include <cstdio>
#include <cstring>
#define maxn 5240
#define inf 0x7fffffff
using namespace std;
struct node
{
int u,v;
int w;
}g[maxn];
int n,m,w;
int dis[maxn];
bool bellman_ford(int len)
{
int i,j;
for (i = 0; i <= n; ++i)
dis[i] = inf;
int flag = 0;
dis[1] = 0;
for (i = 1; i < n; ++i)
{
for (j = 0; j < len; ++j)
{
if (dis[g[j].u] != inf && dis[g[j].u] + g[j].w < dis[g[j].v])//注意这里一定要判断dis[g[j].u] != inf
dis[g[j].v] = dis[g[j].u] + g[j].w;
}
}
for (i = 1; i < n; ++i)
{
if (flag) break;
for (j = 0; j < len; ++j)
{
if (dis[g[j].u] + g[j].w < dis[g[j].v])
{
flag = 1;
break;
}
}
}
if (flag) return true;
else return false;
}
int main()
{
int f,i,len;
int x,y,wi;
scanf("%d",&f);
while (f--)
{
memset(g,0,sizeof(g));
scanf("%d%d%d",&n,&m,&w);
len = 0;
for (i = 0; i < m; ++i)
{
scanf("%d%d%d",&x,&y,&wi);
g[len].u = x;
g[len].v = y;
g[len].w = wi;
len++;
g[len].u = y;
g[len].v = x;
g[len].w = wi;
len++;
}
for (i = 0; i < w; ++i)
{
scanf("%d%d%d",&x,&y,&wi);
g[len].u = x;
g[len].v = y;
g[len].w = -wi;
len++;
}
if (bellman_ford(len)) printf("YES\n");
else printf("NO\n");
}
return 0;
}