|
| 1 | +# 문제 |
| 2 | +맥주 마시면서 걸어가기 |
| 3 | +## 문제 원본 |
| 4 | +문제의 원본은 [여기서](https://www.acmicpc.net/problem/9205) 확인하세요. |
| 5 | + |
| 6 | +## 분류 |
| 7 | +* 그래프 이론 |
| 8 | + |
| 9 | +# 풀이 |
| 10 | + |
| 11 | +그래프에 각정점에서 1000(50 * 20)m이내의 도달할 수 있는 편의점들을 인접 정점으로 추가한다. |
| 12 | +그 이후, 출발지 0에서 부터 깊이 우선 탐색을 진행하여 방문된 정점은 `visited`배열에 기록해 둔다. 너비우선 탐색도 상관없을것 같다. |
| 13 | +`visited[n + 2 - 1]`의 값이 참이면 `happy`를, 거짓이면 `sad`를 출력한다. 이는 곧 최적해가 된다. |
| 14 | + |
| 15 | +``` c++ |
| 16 | +#include <iostream> |
| 17 | +#include <vector> |
| 18 | +#include <cstring> |
| 19 | + |
| 20 | +using namespace std; |
| 21 | + |
| 22 | +class Graph { |
| 23 | +public: |
| 24 | + int n; |
| 25 | + vector<pair<int, int>> *adj; |
| 26 | + |
| 27 | + Graph(int n) { |
| 28 | + this->n = n; |
| 29 | + this->adj = new vector<pair<int, int>>[n]; |
| 30 | + } |
| 31 | + |
| 32 | + void insertEdge(int u, int v, int w) { |
| 33 | + this->adj[u].push_back(make_pair(v, w)); |
| 34 | + } |
| 35 | +}; |
| 36 | + |
| 37 | +int distance(pair<int, int> a, pair<int, int> b) { |
| 38 | + return abs(a.first - b.first) + abs(a.second - b.second); |
| 39 | +} |
| 40 | + |
| 41 | +bool visited[102]; |
| 42 | +void dfs(Graph* g, int v) { |
| 43 | + visited[v] = true; |
| 44 | + |
| 45 | + int size = g->adj[v].size(); |
| 46 | + for (int i = 0; i < size; i++) { |
| 47 | + int u = g->adj[v][i].first; |
| 48 | + if (!visited[u]) { |
| 49 | + dfs(g, u); |
| 50 | + } |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +int main(void) { |
| 55 | + |
| 56 | + int t; |
| 57 | + cin >> t; |
| 58 | + |
| 59 | + for (int z = 0; z < t; z++) { |
| 60 | + int n; |
| 61 | + cin >> n; |
| 62 | + |
| 63 | + memset(visited, false, sizeof(visited)); |
| 64 | + vector<pair<int, int>> coord(n + 2); |
| 65 | + Graph g(n + 2); |
| 66 | + for (int i = 0; i < n + 2; i++) { |
| 67 | + int x, y; |
| 68 | + cin >> x >> y; |
| 69 | + |
| 70 | + coord[i] = make_pair(x, y); |
| 71 | + } |
| 72 | + |
| 73 | + int size = coord.size(); |
| 74 | + for (int i = 0; i < size; i++) { |
| 75 | + for (int j = 0; j < size; j++) { |
| 76 | + int dist = distance(coord[i], coord[j]); |
| 77 | + if (dist <= 1000) { |
| 78 | + g.insertEdge(i, j, dist); |
| 79 | + } |
| 80 | + } |
| 81 | + } |
| 82 | + |
| 83 | + dfs(&g, 0); |
| 84 | + |
| 85 | + cout << visited[n + 2 - 1] << endl; |
| 86 | + |
| 87 | + if (visited[n + 2 - 1]) { |
| 88 | + cout << "happy" << endl; |
| 89 | + } |
| 90 | + else { |
| 91 | + cout << "sad" << endl; |
| 92 | + } |
| 93 | + } |
| 94 | + |
| 95 | + return 0; |
| 96 | +} |
| 97 | +``` |
0 commit comments