[알고리즘/백준] 2869 달팽이는 올라가고 싶다 - 자바(JAVA)

[알고리즘/백준] 2869 달팽이는 올라가고 싶다 - 자바(JAVA)

문제

https://www.acmicpc.net/problem/2869

풀이 코드

처음에는 아래 코드와 같이 반복문을 사용하여 풀이하였는데 시간 초과로 실패하였다..

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int v = Integer.parseInt(st.nextToken()); int day = 0; int sum = 0; while(true) { day++; sum += a; if (sum >= v) { break; } sum -= b; } System.out.println(day); } }

이번 문제는 풀이 방법이 잘 떠오르지 않아 검색을 통해 다른 분의 설명을 참고하여 문제를 해결하였다.

import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class Main { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st = new StringTokenizer(br.readLine()); int a = Integer.parseInt(st.nextToken()); int b = Integer.parseInt(st.nextToken()); int v = Integer.parseInt(st.nextToken()); //정상에 올라간 후에는 미끄러지지 않기 때문에 막대 길이 v에서 마지막 날에 미끌어질 b를 미리 뺀 수를 하루에 올라가는 길이(a-b)로 나눈다. int day = (v-b) / (a-b); //나머지가 있는 경우 하루를 더 올라가야되는 것이기 때문에 하루를 더해준다. if ((v-b) % (a-b) > 0) { day++; } System.out.println(day); } }

풀이에 참고한 블로그 글은 다음과 같다 -> https://st-lab.tistory.com/75

728x90

from http://developer-hm.tistory.com/185 by ccl(A) rewrite - 2021-10-07 19:27:29