原题:点击打开链接
题意:
在n个结点之中,有权值为正的无向路,也有权值为负的有向虫洞,问能不能从起点返回起点之后所用时间为负值。
思路:
明显题目意思就是让求图中有没有负环,有负环则能满足题意。于是用bellman法判断负环存不存在就可以了。
代码:
<pre class="sh_cpp sh_sourceCode" style="font-size:14px; font-family: 'Courier New', Courier, monospace; background-color: white;"><pre name="code" class="cpp">#include <iostream>
#include<string.h>
using namespace std;
struct node
{
int a, b, t;
}path[5300];
int n, m, W, tol;
int dis[510];
const int inf = 0x3f3f3f3f;
bool ford()
{
for(int i = 0;i <= n;i++)
dis[i] = inf;
for(int i = 0;i < n-1;i++)
{
bool flag = false;
for(int j = 0;j < tol;j++)
if(dis[path[j].b] > dis[path[j].a] + path[j].t)
dis[path[j].b] = dis[path[j].a] + path[j].t, flag = true;
if(!flag)
break;
}
for(int i = 0;i <tol;i++)
if(dis[path[i].b] > dis[path[i].a] + path[i].t)
return true;
return false;
}
int main()
{
int F;
cin>>F;
while(F--)
{
cin>>n>>m>>W;
tol = 0;
int u, v, w;
for(int i = 0;i < m;i++)
{
cin>>u>>v>>w;
path[tol].a = u;
path[tol].b = v;
path[tol++].t = w;
path[tol].a = v;
path[tol].b = u;
path[tol++].t = w;
}
for(int i = 0;i < W;i++)
{
int temp;
cin>>path[tol].a>>path[tol].b>>temp;
path[tol++].t = -temp;
}
if(ford())
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}