[백준] 2851번 - 슈퍼 마리오 [Java][C++]
[백준] 2851번 - 슈퍼 마리오 [Java][C++]
1. 문제 풀이
슈퍼 마리오가 얻은 점수가 $100$ 에 최대한 가깝게 하는 문제로 가까운 수가 2개면 큰 값을 선택해야 하며, 버섯은 안먹은 순간부터 뒤에 나오는 버섯은 전부 먹을 수 없다. 그냥 조건문 기반으로 구현하는 방식으로 해결해도 되고 누적합을 활용해서 해결해도 된다.
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
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
int sum = 0;
for (int i = 0; i < 10; i++) {
if (sum + arr[i] <= 100) {
sum += arr[i];
continue;
}
if ((100 - sum) >= (sum + arr[i] - 100)) {
sum += arr[i];
continue;
}
break;
}
System.out.println(sum);
}
}
2. 누적합 [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
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int[] arr = new int[10];
for (int i = 0; i < 10; i++) {
arr[i] = Integer.parseInt(br.readLine());
}
int[] pSum = new int[1 + 10];
for (int i = 1; i <= 10; i++) {
pSum[i] = pSum[i - 1] + arr[i - 1];
}
int ans = 0;
int diff = 1_000;
for (int i = 1; i <= 10; i++) {
if (Math.abs(pSum[i] - 100) <= diff) {
ans = pSum[i];
diff = Math.abs(pSum[i] - 100);
}
}
System.out.println(ans);
}
}
3. 구현 [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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> v(10);
for (auto& x : v) cin >> x;
int sum = 0;
for (int i = 0; i < 10; i++) {
if (sum + v[i] <= 100) {
sum += v[i];
continue;
}
if ((100 - sum) >= (sum + v[i] - 100)) {
sum += v[i];
continue;
}
break;
}
cout << sum;
}
4. 누적합 [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
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
vector<int> v(10);
for (auto& x : v) cin >> x;
vector<int> psum(1 + 10);
for (int i = 1; i <= 10; i++) {
psum[i] = psum[i - 1] + v[i - 1];
}
int ans = 0;
int diff = 1000;
for (int i = 1; i <= 10; i++) {
if (abs(psum[i] - 100) <= diff) {
ans = psum[i];
diff = abs(psum[i] - 100);
}
}
cout << ans;
}
3. 풀이 정보
1. 구현 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 108 ms | 14120 KB | 692 B |
2. 누적합 [Java]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| Java 11 | 104 ms | 14132 KB | 743 B |
3. 구현 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 0 ms | 2020 KB | 463 B |
4. 누적합 [C++]
| 언어 | 시간 | 메모리 | 코드 길이 |
|---|---|---|---|
| C++ 17 | 0 ms | 2020 KB | 505 B |
This post is licensed under CC BY 4.0 by the author.