문제(출처: https://www.acmicpc.net/problem/23895)
< Allocation >
문제 풀이
주택의 값을 오름차순으로 정렬하여 구매할 수 있는 주택의 최대 수를 구한다.
my solution (Java)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
public class _23895_ { // Allocation
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
int T = Integer.parseInt(bf.readLine());
for (int i = 0; i < T; i++) {
st = new StringTokenizer(bf.readLine());
int N = Integer.parseInt(st.nextToken());
int B = Integer.parseInt(st.nextToken());
st = new StringTokenizer(bf.readLine());
int arr[] = new int[N];
for (int j = 0; j < N; j++) {
arr[j] = Integer.parseInt(st.nextToken());
}
Arrays.sort(arr);
int cnt = 0;
for (int j = 0; j < N; j++) {
if (B - arr[j] >= 0) {
B -= arr[j];
cnt += 1;
}
}
bw.write("Case #" + (i + 1) + ": " + cnt + "\n");
}
bw.flush();
}
}
변수)
T : 테스트 케이스 수
N, B : 주택 수, 지출할 예산
arr : 주택 비용
cnt : 구매할 수 있는 주택의 최대 수
테스트 케이스 수를 입력받는다. 테스트 케이스 수만큼 다음 과정을 반복한다.
1) 주택 수 N과 지출할 예산 B를 입력받는다.
2) 주택 수만큼 주택 비용을 입력받아 배열 arr에 저장한다.
3) 배열 arr를 오름차순으로 정렬한다.
4) 배열 arr을 순차 탐색하며 구매할 수 있는 주택의 최대 수를 구한다.
최종 구매할 수 있는 주택의 최대 수를 출력한다.

'🌞Algorithm > 🔥Baekjoon' 카테고리의 다른 글
| [Baekjoon] 5614_問題 3 (0) | 2025.03.31 |
|---|---|
| [Baekjoon] 24755_Election Paradox (0) | 2025.03.27 |
| [Baekjoon] 6566_애너그램 그룹 (0) | 2025.03.25 |
| [Baekjoon] 11597_Excellence (0) | 2025.03.24 |
| [Baekjoon] 6123_O Those Fads (0) | 2025.03.21 |