您的位置:首页 > 编程语言 > C语言/C++

POJ3259(经典bellman判断负权)

2016-08-08 15:13 302 查看
POJ3259

题意:有n个虫洞,问有从一些虫洞穿行过程中因为时间的快慢能遇到自己吗?相对论。

其实题很简单,就是问有没有负权的存在,若有将会一直松弛。

#include<iostream>
using namespace std;

#define INF 0x3f3f3f3f
#define M 5200

int dist[M];
int n,m,f;
int all;

class Node              //一般用结构体或者是类表示起点终点
{
public:
int s,e,t;
}node[M];

int bellman()
{
for(int i = 1;i <= n; i++)
dist[i] = INF;

for(int i = 0;i < n - 1; i++){

bool flag = false;
for(int j = 0;j < all; j++){
if(dist[node[j].e] > dist[node[j].s] + node[j].t){  //松弛每一条边
flag = true;
dist[node[j].e] = dist[node[j].s] + node[j].t;
}
}
if(!flag)
break;
}
for(int i = 0;i < all; i++)
if(dist[node[i].e] > dist[node[i].s] + node[i].t)       //判断负环
return true;
return false;
}

int main()
{
int T;
cin>>T;
while(T--)
{
all = 0;
cin>>n>>m>>f;
for(int i = 0;i < m; i++){      //正权
int a,b,time;
cin>>a>>b>>time;
node[all].s = a;
node[all].e = b;
node[all].t = time;
all++;
node[all].s = b;
node[all].e = a;
node[all].t = time;
all++;
}
for(int i = 0;i < f; i++){      //负权
int a,b,time;
cin>>a>>b>>time;
node[all].s = a;
node[all].e = b;
node[all].t = -time;
all++;
}
if(bellman())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  bellman 算法 poj c++