Skip to content

Commit 163cd9e

Browse files
committed
boj 1865 웜홀
1 parent 195947c commit 163cd9e

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

Bellman-Ford/1865.cpp

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
#include <iostream>
2+
#include <algorithm>
3+
#include <vector>
4+
#define INF 1000000000
5+
using namespace std;
6+
7+
vector<pair<int, int> > weight[501];
8+
bool cyclechk;
9+
int edge[501][501];
10+
int d[501], N, M, W, s, e, t;
11+
12+
void init() {
13+
d[1] = 0;
14+
for (int i = 2; i <= N; i++) {
15+
d[i] = INF;
16+
}
17+
for (int i = 1; i <= N; i++) {
18+
for (int j = 1; j <= N; j++) {
19+
edge[i][j] = INF;
20+
}
21+
}
22+
}
23+
24+
int main() {
25+
cin.tie(NULL); cout.tie(NULL);
26+
ios::sync_with_stdio(false);
27+
28+
int Testcase;
29+
cin >> Testcase;
30+
while (Testcase--) {
31+
cin >> N >> M >> W;
32+
init();
33+
34+
for (int i = 0; i < M; i++) {
35+
cin >> s >> e >> t;
36+
37+
edge[s][e] = min(edge[s][e], t);
38+
edge[e][s] = min(edge[e][s], t);
39+
}
40+
for (int i = 0; i < W; i++) {
41+
cin >> s >> e >> t;
42+
43+
edge[s][e] = min(edge[s][e], -t);
44+
}
45+
46+
for (int i = 1; i <= N; i++) {
47+
for (int j = 1; j <= N; j++) {
48+
if (edge[i][j] < INF) {
49+
weight[i].push_back({ j, edge[i][j] });
50+
}
51+
}
52+
}
53+
54+
for (int i = 1; i <= N; i++) {
55+
for (int j = 1; j <= N; j++) {
56+
for (int k = 0; k < weight[j].size(); k++) {
57+
int next = weight[j][k].first;
58+
int dis = weight[j][k].second;
59+
60+
if (d[next] > d[j] + dis) {
61+
d[next] = d[j] + dis;
62+
if (i == N) cyclechk = true;
63+
}
64+
}
65+
}
66+
}
67+
68+
if (cyclechk) cout << "YES\n";
69+
else cout << "NO\n";
70+
71+
cyclechk = false;
72+
for (int i = 1; i <= N; i++) weight[i].clear();
73+
}
74+
75+
return 0;
76+
}

0 commit comments

Comments
 (0)