https://www.acmicpc.net/problem/2134
그리디 + 구현
예제가 불친절해서 뭔 말인지 깨닫는데 오래 걸림
1. cost는 int 범위를 넘는다.
( 1 * 10000) + (1 * 10000)
...
( 10000 * 10000) + (10000 * 10000)
=> 9999 * 10000 / 2 * 10000 * 2
2. 인부 개수 k는 상관 없다.
한 명이 전부 옮겨도 만 명이 옮기는 것과 같다.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
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 N = Integer.parseInt(st.nextToken());
int M = Integer.parseInt(st.nextToken());
Integer.parseInt(st.nextToken());
int from = 1;
int to = 1;
long cost = 0;
int cnt = 0;
int[] n = new int[N + 1];
int[] m = new int[M + 1];
for (int i = 1; i <= N; i++) {
n[i] = Integer.parseInt(br.readLine());
}
for (int i = 1; i <= M; i++) {
m[i] = Integer.parseInt(br.readLine());
}
while (from <= N && to <= M) {
// 옮길 수 있는 최대량
int fb = n[from];
int tb = m[to];
if (fb == 0) {
from++;
} else if (tb == 0) {
to++;
}
// 다 옮길 수 있음
else if (fb <= tb) {
cnt += fb;
cost += fb * from + fb * to;
m[to] -= fb;
from++;
}
// 다 옮길 수 없음
else {
cnt += tb;
cost += tb * from + tb * to;
n[from] -= tb;
to++;
}
}
System.out.println(String.format("%d %d", cnt, cost));
}
}
'[백준] PS > Java [실랜디]' 카테고리의 다른 글
[백준 2303] 숫자 게임 - JAVA (0) | 2025.03.09 |
---|---|
[백준 2238] 경매 - JAVA (0) | 2025.03.09 |
[백준 1972] 놀라운 문자열 - JAVA (0) | 2025.03.07 |
[백준 2012] 등수 매기기 - JAVA (1) | 2025.03.07 |
[백준 1940] 주몽 - JAVA (1) | 2025.03.06 |