很明显这是一个很扯淡的故事,不过为了出一道带负权值的题目也是难为了出题人,迪杰斯特拉算法不能处理带有负权值的问题,佛洛依德倒是可以,不过复杂度很明显太高,所以spfa是不错的选择,只需要判断出发点时间是否变小.
#include<algorithm>
#include<queue>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<math.h>
using namespace std;
const int maxn = 505;
const int oo = 0xfffffff;
struct node
{
int y, time;
node(int y, int t):y(y), time(t){}
};
vector<node> G[maxn];
int v[maxn];
int spfa(int s)
{
queue<int> Q;
Q.push(s);
while(Q.size())
{
s = Q.front();Q.pop();
int len = G[s].size();
for(int i=0; i<len; i++)
{
node q = G[s][i];
if(v[s]+q.time < v[q.y])
{
v[q.y] = v[s] + q.time;
Q.push(q.y);
}
}
if(v[1] < 0)
return 1;
}
return 0;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
int N, M, W, i, a, b, c;
scanf("%d%d%d", &N, &M, &W);
for(i=1; i<=N; i++)
{
v[i] = oo;
G[i].clear();
}
v[1] = 0;
for(i=0; i<M; i++)
{
scanf("%d%d%d", &a, &b, &c);
G[a].push_back(node(b, c));
G[b].push_back(node(a, c));
}
for(i=0; i<W; i++)
{
scanf("%d%d%d", &a, &b, &c);
G[a].push_back(node(b, -c));
}
int ans = spfa(1);
if(ans == 1)
printf("YES\n");
else
printf("NO\n");
}
return 0;