5014번 - 스타트 링크
간단한 BFS 문제였다.
각 층을 정점으로 위 아래로만 움직일 수 있는 간선이 존재한다고 생각하고 풀었다.
dist 를 구해야했기 때문에, visited 는 따로 안쓰고 dist 로 모두 구현했다.
<정답 코드>
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 | #include<iostream> #include<queue> #include<string.h> using namespace std; bool visited[1000001]; int dist[1000001]; int ans = 0; int dx[2] = { 1,-1 }; int main() { int F, S, G, U, D; cin >> F >> S >> G >> U >> D; memset(dist, -1, sizeof(dist)); queue<int> q; q.push(S); dist[S] = 0; while (!q.empty()) { int now = q.front(); q.pop(); if (now == G) { break; } for (int d = 0; d < 2; d++) { int next; if (d == 0) { next = now + dx[d] * U; } if (d == 1) { next = now + dx[d] * D; } if (next <= F && next >= 1 && dist[next]==-1) { q.push(next); visited[next] = true; dist[next] = dist[now] + 1; } } } if (dist[G] == -1) { cout << "use the stairs" << endl; } else { cout << dist[G] << endl; } return 0; } | cs |
반응형