[Softeer] level 2. 금고털이

Loopy·2023년 11월 23일
0

코테 문제들

목록 보기
14/113


✅ 연관된 두 개의 값 저장하는 방법

ArrayList<int[]> arr = new ArrayList<>();

ArrayList<int[]> arr = new ArrayList<>();

	for (int i = 0; i < N; i++) {
		st = new StringTokenizer(br.readLine());
		int metalW = Integer.parseInt(st.nextToken());
		int P = Integer.parseInt(st.nextToken());
		arr.add(new int[] {metalW, P});
	}

	for (int[] array : arr) {
	    for (int element : array) { System.out.print(element + " ");
	}
	
System.out.println(); 

✅ ' += , = ' 에 따른 결과 값 차이

result += left * value;

아래 두 코드는 단지 result += 와 = 의 처이이다.

for (int[] array : arr) {
			//array[0] = 금속 무게, array[1] = 금속 가치
			while (sum <= W) {
				sum += array[0];
				result += array[0] * array[1];
				System.out.println("결과: " + result);
				count++;
				if (sum < W) {
					int value = arr.get(count)[1];
					int left = W - sum;
					result += left * value;
					System.out.println("작을 때 결과: " + result);
				}
			}
		}
for (int[] array : arr) {
			//array[0] = 금속 무게, array[1] = 금속 가치
			while (sum <= W) {
				sum += array[0];
				result += array[0] * array[1];
				System.out.println("결과: " + result);
				count++;
				if (sum < W) {
					int value = arr.get(count)[1];
					int left = W - sum;
					result = left * value;
					System.out.println("작을 때 결과: " + result);
				}
			}
		}

하지만, 결과값은 각각 310, 170으로 다르게 나온다.
이 말인 즉슨 result += 를 하면 앞에서 계산된 결과에 다시 계산된 결과가 중첩되어 나온다는 말이다.
아, result가 while문 안에 선언되어 있지 않고 while 문 밖에 선언되어 있기 때문에 result 값이 0으로 초기화되지 않고 축척되는구나!
이해했다.

+==

✅ 미처 생각지 못한 것

테스트 케이스 한 개만 맞다. ㅋㅋ
뭘 놓쳤을까.

for-each 문 안에 while문을 넣으면 첫 번째 [20,5]에 대해서 계속 반복을 하니,, out of index가 나고, 20-> 40 -> 60으로 되는 것이였다.

W -= array[0]; 를 해주면 더 쉽게 풀린다.

for (int[] array : arr) {
			// array[0] = 금속 무게, array[1] = 금속 가치
			if (sum >= W) {
				result = W * array[1];
			} else {
				result += array[0] * array[1];
				W -= array[0];
			}
		}

✅ 코드

import java.io.*;
import java.util.*;

public class Main {


	public static void main(String[] args) throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		st = new StringTokenizer(br.readLine());
		int W = Integer.parseInt(st.nextToken());
		int N = Integer.parseInt(st.nextToken());
		//두 개의 값이 들어갈 수 있다.
		ArrayList<int[]> arr = new ArrayList<>();

		for (int i = 0; i < N; i++) {
			st = new StringTokenizer(br.readLine());
			int metalW = Integer.parseInt(st.nextToken());
			int P = Integer.parseInt(st.nextToken());
			arr.add(new int[] {metalW, P});
		}

		//2번째 요소를 기준으로 내림차순
		Collections.sort(arr, Comparator.comparingInt((int[] a)
        -> a[1]).reversed());

		int result = 0;

		for (int[] array : arr) {
			// array[0] = 금속 무게, array[1] = 금속 가치
			// 70 90

			if (W <= array[0]) {
				result += W * array[1];
				break;
			} else {
				result += array[0] * array[1];
				W -= array[0];
			}
		}

		System.out.println(result);

	}
}

profile
잔망루피의 알쓸코딩

0개의 댓글