본문 바로가기
Algorithm/C++

[백준 5014] 스타트링크

by imagineer_jinny 2022. 9. 4.

5014번: 스타트링크 (acmicpc.net)

 

5014번: 스타트링크

첫째 줄에 F, S, G, U, D가 주어진다. (1 ≤ S, G ≤ F ≤ 1000000, 0 ≤ U, D ≤ 1000000) 건물은 1층부터 시작하고, 가장 높은 층은 F층이다.

www.acmicpc.net

 

내 풀이 - 런타임에러남

#include <bits/stdc++.h>
using namespace std;

int f, s, g, u, d;
int dist[1000002];

int main(void) {
    ios::sync_with_stdio(0);
    cin.tie(0);

    cin >> f >> s >> g >> u >> d;
    fill(dist + 1, dist + f + 1, -1);

    queue<int> q;
    q.push(s);
    dist[s] = 1;
    int cnt = 0;
    while ((q.front() != g) || q.empty())
    {
        if (dist[g] == 1)break;

        int x = q.front();
        q.pop();
        
        if (g >= x)
        {
            if (x > f||dist[x] != -1)continue;
            if (u == 0)
            {
                cout << "use the stairs";
                return 0;
            }
            q.push(x + u);
            dist[x + u] = 1;
            cnt++;
        }
        else
        {
            if (x <= 0||dist[x] != -1)continue;
            if (d == 0)
            {
                cout << "use the stairs";
                return 0;
            }
            q.push(x - d);
            dist[x - d] = 1;
            cnt++;

        }
    }
    if (dist[g] == 1)
    {
        cout << cnt;
    }
    else
    {
        cout << "use the stairs";
    }
    return 0;
}

 

정답 풀이

// Authored by : std-freejia
// Co-authored by : BaaaaaaaaaaarkingDog
// http://boj.kr/8f34874217304e3ca3a499f672788d70
#include <bits/stdc++.h>
using namespace std;

int f, s, g, u, d;
int dist[1000002];

int main(void) {
  ios::sync_with_stdio(0);
  cin.tie(0);

  cin >> f >> s >> g >> u >> d;
  fill(dist+1, dist+f+1, -1);
  
  queue<int> q;
  dist[s] = 0; // 현재 위치의 거리를 0으로 둠
  q.push(s); // s층에서 시작
  while(!q.empty()){
    int cur = q.front(); q.pop();
    for(auto nxt : {cur + u, cur - d}){
      if(nxt > f || nxt <= 0 || dist[nxt] != -1) continue;
      dist[nxt] = dist[cur] + 1;
      q.push(nxt);
    }
  }

  if(dist[g] == -1) cout << "use the stairs";
  else cout << dist[g];
}

 

'Algorithm > C++' 카테고리의 다른 글

[백준 6593] 상범 빌딩 (tuple 사용법)  (0) 2022.09.06
[백준 2468] 안전 영역  (0) 2022.09.06
[백준 2667] 단지번호붙이기  (0) 2022.09.04
[백준 2583] 영역 구하기  (0) 2022.09.04
[백준 17298] 오큰수  (0) 2022.09.03

댓글