개발지식 먹는 하마 님의 블로그

13305번 - 주유소 본문

coding

13305번 - 주유소

devhippo 2025. 2. 26. 11:23

✏️ 문제 풀이

  • long 사용
    입력받는 변수는 1,000,000,000이기 때문에 정수형 사용이 가능하다.
    그러나, 최대값이 1,000,000,000인 두 변수를 연산하기 때문에 그 결과는
    int의 표현 범위를 벗어날 수 있다.
    따라서, long 자료형을 사용하는 것이 좋다.
    (int로 받아도 무방하나 연산을 위해 long으로 형변환을 해줘야 하는 노고가 있기 때문이다.)

1) 이동한 도시의 주유비가 현재 최소 주유비보다 쌀 경우, 최소 주유비를 해당 값으로 변경한다.

long result = 0;
long minCost = 1000000000;
for (int i = 0; i < costs.size()-1; i++){
    long cost = costs.get(i);
}

2) 이동할 때마다 이동 * 최소 주유비 값을 합계에 더한다.

if(cost  < minCost){
   minCost = cost;
}
result += minCost * distances.get(i);

🖥️ 코드

 

class Main {
    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
		//입력값 받기
        int N = sc.nextInt();
        ArrayList<Long> distances = new ArrayList<>();
        for(int i = 0; i < N-1; i++){
            long distance = sc.nextLong();
            distances.add(distance);
        }

        ArrayList<Long> costs = new ArrayList<>();
        for(int i = 0; i < N; i++){
            long cost = sc.nextLong();
            costs.add(cost);
        }
        
		//알고리즘
        long result = 0;
        long minCost = 1000000000;
        for (int i = 0; i < costs.size()-1; i++){
            long cost = costs.get(i);
            if(cost  < minCost){
                minCost = cost;
            }
            result += minCost * distances.get(i);
        }

        System.out.println(result);
        sc.close();
    }
}

'coding' 카테고리의 다른 글

1316번 - 그룹 단어 체커  (0) 2025.02.28
1541번 - 잃어버린 괄호  (0) 2025.02.27
1931번 - 회의실 배정  (0) 2025.02.25
1992번 - 쿼드트리  (0) 2025.02.24
1654번 - 이분 탐색 - 랜선 자르기  (0) 2025.02.07