File tree Expand file tree Collapse file tree 1 file changed +69
-0
lines changed
Expand file tree Collapse file tree 1 file changed +69
-0
lines changed Original file line number Diff line number Diff line change 1+ // https://www.acmicpc.net/problem/1865
2+ #include < iostream>
3+ #include < algorithm>
4+ #include < vector>
5+ #include < cstring>
6+
7+ using namespace std ;
8+
9+ /*
10+ 벨만포드 O(VE)
11+ 1. V - 1개만큼 모든 노드 간선 순회
12+ 2. V에도 줄어들면 음수 사이클 존재
13+ */
14+
15+ struct Edge {
16+ int n, cost;
17+ };
18+
19+ int N, M, W;
20+ const long long INF = 1e12 ;
21+
22+ vector<long long > dist;
23+ vector<vector<Edge>> graph;
24+
25+ bool bellmanford (){
26+ dist.assign (N + 1 , INF);
27+
28+ for (int k = 1 ; k <= N; k++){
29+ for (int i = 1 ; i <= N; i++){
30+ for (int j = 0 ; j < graph[i].size (); j++){
31+ int next = graph[i][j].n ;
32+ int nextcost = graph[i][j].cost ;
33+
34+ if (dist[next] > dist[i] + nextcost) {
35+ dist[next] = dist[i] + nextcost;
36+ // N번째에도 값이 변경되면 음수 사이클 존재
37+ if (k == N) return true ;
38+ }
39+ }
40+ }
41+ }
42+ return false ;
43+ }
44+
45+ int main (){
46+ ios_base::sync_with_stdio (false );
47+ cin.tie (NULL ); cout.tie (NULL );
48+
49+ int TC;
50+ cin >> TC;
51+ while (TC--) {
52+ cin >> N >> M >> W;
53+ int S, E, T;
54+ graph.resize (N + 1 );
55+ for (int i = 0 ; i < M; i++){ // 무방향
56+ cin >> S >> E >> T;
57+ graph[S].push_back ({E, T});
58+ graph[E].push_back ({S, T});
59+ }
60+ for (int i = 0 ; i < W; i++){ // 방향
61+ cin >> S >> E >> T;
62+ graph[S].push_back ({E, -T});
63+ }
64+
65+ if (bellmanford ()) cout << " YES\n " ;
66+ else cout << " NO\n " ;
67+ graph.clear ();
68+ }
69+ }
You can’t perform that action at this time.
0 commit comments