반응형
문제 출처 :
https://www.acmicpc.net/problem/1219
알고리즘 분석 :
문제 해결에 필요한 사항
1. 벨만 포드 알고리즘 :: http://www.crocus.co.kr/search/%EB%B2%A8%EB%A7%8C%ED%8F%AC%EB%93%9C
이 문제는 도착시 벌 수 있는 돈을 +로, 가는데 드는 경비를 -로두면 벨만 포드 알고리즘으로 문제를 해결 할 수 있다.
이때 벨만포드 코드 속에 if(cnt == v-1)일때 배열에 담는 코드가 있는데, 이 문제는 돈을 버는 사이클이 존재할 때
그 사이클이 도착점으로 이어진다면 gee를 출력해야한다.
따라서 벨만포드 속 if문에서 사이클에 해당하는 점들을 모두 모아두고, 벨만포드가 끝난 후, 각 사이클에 연관된 정점에 대해
bfs를 돌려서 정점이 도착점으로 갈 수 있는지 확인해준다.
만약 도착한다면 gee, 도착하지 않는다면 돈을 버는 최댓 값, 경로에 도착하지도 못한다면 gg를 출력한다.
이때 조심해야 할 점은, 인접행렬로 하지않고, 인접 리스트로 푸는 것을 추천한다.
필자가 인접 행렬로 계속 풀다가 많은 W/A를 받았는데, 같은 경로로 가는 입력이 주어지고 다른 비용이 드는 입력이 주어질 경우가 존재하기 때문이다.
소스 코드 :
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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | #include <iostream> #include <cstdio> #include <vector> #include <memory.h> #include <queue> #define INF 1LL << 60 using namespace std; typedef pair<int, int> pii; typedef long long ll; ll dist[111]; ll cost[111]; bool getGee[111]; vector<pii> adj[111]; bool visit[111]; int main() { int V, E, start, end; int cnt = 0; scanf("%d %d %d %d", &V, &start, &end, &E); for (int i = 0; i < E; i++) { int from, to, val; scanf("%d %d %d", &from, &to, &val); adj[from].push_back({ to, val }); } for (int i = 0; i < V; i++) scanf("%lld", &cost[i]); for (int i = 0; i < V; i++) dist[i] = -INF; dist[start] = cost[start]; // 벨만포드 bool update = true; bool ok = false; while (update && cnt != V) { update = false; for (int i = 0; i < V; i++) for(auto j : adj[i]) { if (dist[i] != -INF && dist[i] + cost[j.first] - j.second > dist[j.first]) { dist[j.first] = dist[i] + cost[j.first] - j.second; update = true; if (cnt == V - 1) getGee[i] = true; } } cnt++; } // bfs bool getChk = false; queue<int> q; for (int i = 0; i < V; i++) if (getGee[i]) q.push(i); while (!q.empty()) { int here = q.front(); q.pop(); if (visit[here]) continue; visit[here] = true; for (int i = 0; i < adj[here].size(); i++) { if (adj[here][i].first == end) { getChk = true; break; } if(!visit[adj[here][i].first]) q.push(adj[here][i].first); } if (getChk) break; } if (dist[end] == -INF) printf("gg"); else if (getChk) printf("Gee"); else printf("%lld", dist[end]); return 0; } // This source code Copyright belongs to Crocus // If you want to see more? click here >> | Crocus |
반응형
'Applied > 알고리즘 문제풀이' 카테고리의 다른 글
[Codeground 46번] 할인권 (0) | 2017.05.01 |
---|---|
[13265번] 색칠하기 (0) | 2017.05.01 |
[9663번] N-Queen (0) | 2017.04.27 |
[1377번] 버블 소트 (0) | 2017.04.27 |
[1915번] 가장 큰 정사각형 (0) | 2017.04.26 |