SPFA找负环-----------虫洞

农夫约翰在巡视他的众多农场时,发现了很多令人惊叹的虫洞。
虫洞非常奇特,它可以看作是一条 单向 路径,通过它可以使你回到过去的某个时刻(相对于你进入虫洞之前)。
农夫约翰的每个农场中包含N片田地,M条路径(双向)以及W个虫洞。
现在农夫约翰希望能够从农场中的某片田地出发,经过一些路径和虫洞回到过去,并在他的出发时刻之前赶到他的出发地。
他希望能够看到出发之前的自己。
请你判断一下约翰能否做到这一点。
下面我们将给你提供约翰拥有的农场数量F,以及每个农场的完整信息。
已知走过任何一条路径所花费的时间都不超过10000秒,任何虫洞将他带回的时间都不会超过10000秒。
输入格式
第一行包含整数F,表示约翰共有F个农场。
对于每个农场,第一行包含三个整数N,M,W。
接下来M行,每行包含三个整数S,E,T,表示田地S和E之间存在一条路径,经过这条路径所花的时间为T。
再接下来W行,每行包含三个整数S,E,T,表示存在一条从田地S走到田地E的虫洞,走过这条虫洞,可以回到T秒之间。
输出格式
输出共F行,每行输出一个结果。
如果约翰能够在出发时刻之前回到出发地,则输出“YES”,否则输出“NO”。
数据范围
1≤F≤51≤F≤5

1≤N≤5001≤N≤500,

1≤M≤25001≤M≤2500,

1≤W≤2001≤W≤200,

1≤T≤100001≤T≤10000,

1≤S,E≤N1≤S,E≤N
输入样例:
2
3 3 1
1 2 2
1 3 4
2 3 1
3 1 3
3 2 1
1 2 3
2 3 4
3 1 8

输出样例:
NO
YES

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 510, M = 5210;
int n, m1, m2;
int h[N], e[M], w[M], ne[M], idx;
int dist[N];
int q[N], cnt[N];
bool st[N];
void add(int a, int b, int c){
 e[idx] = b, w[idx] = c, ne[idx] = h[a], h[a] = idx ++;
}
bool spfa(){
 memset(dist, 0, sizeof dist);
 memset(cnt, 0, sizeof cnt);
 memset(st, 0, sizeof st);
  int hh = 0, tt = 0;
 for (int i = 1; i <= n; i ++){
  q[tt ++] = i;
  st[i] = true;
 }
  while(hh != tt){
  int t = q[hh ++];
  if (hh == N)   hh = 0;
  st[t] = false;
   for (int i = h[t]; ~i; i = ne[i]){
   int j = e[i];
   if (dist[j] > dist[t] + w[i]){
    dist[j] = dist[t] + w[i];
    cnt[j] = cnt[t] + 1;
    if (cnt[j] >= n)    return true;
    if (!st[j]){
     q[tt ++] = j;
     if (tt == N)   tt = 0;
     st[j] = true;
    }
   }
  }
 }
  return false;
}
int main(){
 int T;
 cin >> T;
 while(T --){
  scanf("%d%d%d", &n, &m1, &m2);
  memset(h, -1, sizeof h);
  idx = 0;
    for (int i = 0; i < m1; i ++){
   int a, b, c;
   scanf("%d%d%d", &a, &b, &c);
   add(a, b, c), add(b, a, c);
  }
    for (int i = 0; i < m2; i ++){
   int a, b, c;
   scanf("%d%d%d", &a, &b, &c);
   add(a, b, -c);
  }
    if (spfa())    puts("YES");
  else           puts("NO");
 }
  return 0;
}
发布了164 篇原创文章 · 获赞 112 · 访问量 6771

猜你喜欢

转载自blog.csdn.net/qq_45772483/article/details/105469818