[BaekJoon] 18186번 - 라면 사기 (Large) [Java][C++]
[BaekJoon] 18186번 - 라면 사기 (Large) [Java][C++]
1. 문제 풀이
BaekJoon 18185번 - 라면 사기 (Small) 문제에서 3원과 2원이 $B$ 원과 $C$ 원으로 바뀐 문제로 $B \ge C$ 면 이전과 동일한 원리로 풀면 되고, $B < C$ 면 세트로 사는 것이 손해이므로 전부 첫 번째 방법으로 구매하면 된다.
2. 코드
1. 풀이 [Java]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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 = new StringTokenizer(br.readLine());
int n = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
int[] arr = new int[2 + n];
st = new StringTokenizer(br.readLine());
for (int i = 2; i < 2 + n; i++) {
arr[i] = Integer.parseInt(st.nextToken());
}
if (b <= c) {
long cnt = 0;
for (int x : arr) {
cnt += x;
}
System.out.println(cnt * b);
} else {
long[][] cnt = new long[2 + n][3];
for (int i = 2; i < 2 + n; i++) {
long x = arr[i];
long[] prev = cnt[i - 1];
if (x >= prev[0]) {
cnt[i][1] = prev[0];
x -= prev[0];
} else {
cnt[i][1] = x;
continue;
}
if (x >= prev[1]) {
cnt[i][2] = prev[1];
x -= prev[1];
} else {
cnt[i][2] = x;
continue;
}
cnt[i][0] = x;
}
long sum = 0;
for (long[] row : cnt) {
sum += b * row[0] + c * (row[1] + row[2]);
}
System.out.println(sum);
}
}
}
2. 풀이 [C++]
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <bits/stdc++.h>
using namespace std;
long long arr[1000002];
long long cnt[1000002][3];
int main() {
ios::sync_with_stdio(0);
cin.tie(0);
int n, b, c;
cin >> n >> b >> c;
for (int i = 2; i < 2 + n; i++) {
cin >> arr[i];
}
if (b <= c) {
long long cnt = 0;
for (int i = 2; i < 2 + n; i++) {
cnt += arr[i];
}
cout << cnt * b;
} else {
for (int i = 2; i < 2 + n; i++) {
long long x = arr[i];
if (x >= cnt[i - 1][0]) {
cnt[i][1] = cnt[i - 1][0];
x -= cnt[i - 1][0];
} else {
cnt[i][1] = x;
continue;
}
if (x >= cnt[i - 1][1]) {
cnt[i][2] = cnt[i - 1][1];
x -= cnt[i - 1][1];
} else {
cnt[i][2] = x;
continue;
}
cnt[i][0] = x;
}
long long sum = 0;
for (int i = 2; i < 2 + n; i++) {
sum += b * cnt[i][0] + c * (cnt[i][1] + cnt[i][2]);
}
cout << sum;
}
}
This post is licensed under CC BY 4.0 by the author.