poj

链接:https://vjudge.net/problem/POJ-3259

思路:一个裸着的判断是否存在负环即可,可用Bellman-Ford算法判断负环的形式,但是一定要注意,秘密通道和走廊是可以同时存在,也就是既要花费时间也要回溯时间。

代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include<iostream>
#include<cstring>
using namespace std;

struct edge{
int from,to,cost;
};

edge es[5500];

int d[5500];
const int INF = 1e9;
int n,m,w,t=0;
//Bellman-Ford算法判断负环的形式
bool findf(){
memset(d,0,sizeof(d));
for(int i=0;i<n;i++){
for(int j=0;j<t;j++){
edge e = es[j];
if(d[e.to]>d[e.from]+e.cost){
d[e.to] = d[e.from] + e.cost;
if(i==n-1)return true;
}
}
}
return false;
}

int main(){
int q;
cin>>q;
while(q--){
cin>>n>>m>>w;
t = 0;
for(int i=0;i<m;i++){
int from,to,cost;
cin>>from>>to>>cost;
from--;
to--;
es[t].from = from;
es[t].to = to;
es[t].cost = cost;
t++;
//注意这是一个无向图
es[t].from = to;
es[t].to = from;
es[t].cost = cost;
t++;
}
for(int i=0;i<w;i++){
int from,to,cost;
cin>>from>>to>>cost;
--from;
--to;
es[t].from = from;
es[t].to = to;
es[t].cost = -cost;
t++;
}
if(findf())cout<<"YESn";
else cout<<"NOn";
}
return 0;
}