코드의 기준은
https://www.acmicpc.net/problem/11657
제일 중요한 것은 45~46번째 줄이라고 생각한다.
그리고 밑의 코드를 그대로 붙이면 틀릴것이다. 이유는 질문 게시판에 가면 알 수 있다.
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
|
#include <iostream>
#define ll long long int
#define pii pair<int, int>
#define INF 987654321
using namespace std;
class Edge
{
public :
int st;
int en;
int di;
};
Edge edge[6000];
int v, e;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
cin >> v >> e;
int st, en, di;
for (int i = 0; i < e; i++)
{
cin >> st >> en >> di;
edge[i] = { st,en,di };
}
int ans[501];
ans[1] = 0;
for (int i = 2; i <= v; i++)
ans[i] = INF;
int nega_cycle = 0;
for (int i = 0; i < v; i++)
{
for (int j = 0; j < e; j++)
{
Edge e = edge[j];
// 만약 이걸 체크 안해주면 edge[j].dist가 -일때 밑에 IF문이 갱신되어버린다.
if (ans[e.st] == INF)
continue;
if (ans[e.en] > ans[e.st] + e.di)
{
if (i == v-1)
nega_cycle = 1;
ans[e.en] = ans[e.st] + e.di;
}
}
}
if (nega_cycle == 1)
cout << -1;
else
{
for (int i = 2; i <= v; i++)
{
if (ans[i] == INF)
cout << -1 << '\n';
else
cout << ans[i] << '\n';
}
}
}
|
cs |