0%

BZOJ 1715 解题报告

题意简述

多组数据,给定一个有\(n\)个点\(m\)条边的有向带权图,如果图中存在负环输出"YES",否则输出"NO"。

时间限制(总):5s 空间限制:128MB

题目链接

BZOJ 1715

题解

求负环的模板题。由于题目仅要求求负环,且bfs-SPFA求负环的效率不是很高,所以采用dfs-SPFA来求负环。

代码

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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
#include <cstdio>
#include <algorithm>
#include <cstring>

using namespace std;

const int MAXN = 510;
const int MAXM = 6100;

template<typename T>
T read() {
T result = 0;int f = 1;char c = getchar();
while(c > '9' || c < '0') {if(c == '-') f *= -1;c = getchar();}
while(c <= '9' && c >= '0') {result = result * 10 + c - '0';c = getchar();}
return result * f;
}

struct Graph {
struct Edge {
int next,to,weight;
};
Edge edges[MAXM];
int tot,heads[MAXN];

Graph() : tot(0) {
memset(heads,-1,sizeof(heads));
}

void addEdge(int u,int v,int w) {
edges[tot].to = v;
edges[tot].next = heads[u];
edges[tot].weight = w;
heads[u] = tot++;
}

void clear() {
tot = 0;
memset(heads,-1,sizeof(heads));
}
} graph;

int dis[MAXN];
bool visit[MAXN],found;


void spfa(int now) {
visit[now] = true;
for(int i = graph.heads[now];i != -1;i = graph.edges[i].next) {
Graph::Edge &tmpEdge = graph.edges[i];
if(dis[tmpEdge.to] <= dis[now] + tmpEdge.weight) continue;
if(visit[tmpEdge.to]) {
found = true;
return;
}
dis[tmpEdge.to] = dis[now] + tmpEdge.weight;
spfa(tmpEdge.to);
if(found) return;
}
visit[now] = false;
}

void init() {
graph.clear();
memset(dis,0,sizeof(dis));
memset(visit,0,sizeof(visit));
found = false;
}

int main() {
int F = read<int>();
while(F--) {
init();
int N = read<int>(),M = read<int>(),W = read<int>();
for(int i = 0;i < M;i++) {
int u = read<int>(),v = read<int>(),w = read<int>();
graph.addEdge(u,v,w);
graph.addEdge(v,u,w);
}
for(int i = 0;i < W;i++) {
int u = read<int>(),v = read<int>(),w = read<int>();
graph.addEdge(u,v,-w);
}
for(int i = 1;i <= N;i++) {
spfa(i);
if(found) {
break;
}
}
if(found) {
printf("YES\n");
}else {
printf("NO\n");
}
}
return 0;
}