讲的是有n个农场,m条路,w个虫洞,正常的路径使人从a到b,花费t时间,虫洞可以使人从a到b,且时间回到t之前。问有个人出发到返回能不能看到以前的自己,也就是判断是否存在负环。
代码分两种,一种遍历所有的点,如果这个点连接虫洞,那么以这个点为源点进行spfa判负环,把所有的点遍历一遍即可得出答案;
还有一种比较巧妙,建立一个超级源点连接所有的带父权值的边的一个点,这样从源点出发,就可以判断所有情况。
第二种代码如下:
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#define inf 0x3f3f3f3f
using namespace std;
const int maxn = 1005;
int n, m, s, t, p; //n为点数 s为源点
int head[maxn]; //head[from]表示以head为出发点的邻接表表头在数组es中的位置,开始时所有元素初始化为-1
int d[maxn]; //储存到源节点的距离,在Spfa()中初始化
int cnt[maxn];
bool inq[maxn]; //这里inq作inqueue解释会更好,出于习惯使用了inq来命名,在Spfa()中初始化
int nodep; //在邻接表和指向表头的head数组中定位用的记录指针,开始时初始化为0
struct node {
int v, w, next;
}es[10005];
void init() {
for(int i = 0; i <= n; i++) {
d[i] = inf;
inq[i] = false;
cnt[i] = 0;
head[i] = -1;
}
nodep = 0;
}
void addedge(int from, int to, int weight)
{
es[nodep].v = to;
es[nodep].w = weight;
es[nodep].next = head[from];
head[from] = nodep++;
}
bool spfa()
{
queue<int> que;
d[s] = 0; //s为源点
inq[s] = 1;
que.push(s);
while(!que.empty()) {
int u = que.front();
que.pop();
inq[u] = false; //从queue中退出
//遍历邻接表
for(int i = head[u]; i != -1; i = es[i].next) { //在es中,相同from出发指向的顶点为从head[from]开始的一项,逐项使用next寻找下去,直到找到第一个被输
//入的项,其next值为-1
int v = es[i].v;
if(d[v] > d[u] + es[i].w) { //松弛(RELAX)操作
d[v] = d[u] + es[i].w;
if(!inq[v]) { //若被搜索到的节点不在队列que中,则把to加入到队列中去
inq[v] = true;
que.push(v);
if(++cnt[v] > n) {
return false;
}
}
}
}
}
return true;
}
int main()
{
int T;
cin >> T;
while(T--) {
cin >> n >> m >> p;
int a, b, c;
init();
while(m--) {
cin >> a >> b >> c;
addedge(a, b, c);
addedge(b, a, c);
}
while(p--) {
cin >> a >> b >> c;
addedge(a, b, -c);
addedge(0, a, 0);
}
s = 0;
if(!spfa()) {
cout << "YES" << endl;
}
else {
cout << "NO" << endl;
}
}
return 0;
}