2579번: 계단 오르기
계단 오르기 게임은 계단 아래 시작점부터 계단 꼭대기에 위치한 도착점까지 가는 게임이다. <그림 1>과 같이 각각의 계단에는 일정한 점수가 쓰여 있는데 계단을 밟으면 그 계단에 쓰여 있는 점
www.acmicpc.net
- 생각
현재 계단이 i일 때, 그 전 계단 i-1을 밟고 올라왔는지 아닌지로 나눠서 계산한다. 계단을 밟는 개수는 최소가 되어야 하므로 전 단계 i-1을 밟았으면 그 전전 단계 i-2는 점프했다고 가정한다. 그래서 현재 계단까지의 최대값 dp[i]는 지금 계단의 값 steps[i], 전 단계 steps[i-1]과 점프 전 최대값 dp[i-3]의 합이다. 만약 전 단계 i-1을 밟지않고 점프했다면, dp[i]는 현재 값 steps[i]와 점프한 최대값 dp[i-2]의 합이다. 이 둘 중 큰 값을 dp[i]에 저장하면 된다.
- 코드
import java.io.IOException;
import java.io.InputStream;
import java.util.InputMismatchException;
public class Main {
static int n;
static int[] dp;
public static void main(String[] args) throws Exception {
SetData();
System.out.println(dp[n]);
}
private static void SetData() throws Exception {
InputReader in = new InputReader(System.in);
n = in.nextInt();
int[] steps = new int[n+1];
dp = new int[n+1];
int noJump = 0, jump = 0;
for(int i = 1; i <= n; i++)
steps[i] = in.nextInt();
dp[1] = steps[1];
if(n>=2)
dp[2] = steps[1] + steps[2];
for(int i = 3; i <= n; i++) {
noJump = steps[i] + steps[i-1] + dp[i-3];
jump = steps[i] + dp[i-2];
dp[i] = Math.max(noJump, jump);
}
}
}
class InputReader {
private final InputStream stream;
private final byte[] buf = new byte[8192];
private int curChar, snumChars;
public InputReader(InputStream st) {
this.stream = st;
}
public int read() {
if (snumChars == -1)
throw new InputMismatchException();
if (curChar >= snumChars) {
curChar = 0;
try {
snumChars = stream.read(buf);
} catch (IOException e) {
throw new InputMismatchException();
}
if (snumChars <= 0)
return -1;
}
return buf[curChar++];
}
public int nextInt() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
int res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public long nextLong() {
int c = read();
while (isSpaceChar(c)) {
c = read();
}
int sgn = 1;
if (c == '-') {
sgn = -1;
c = read();
}
long res = 0;
do {
res *= 10;
res += c - '0';
c = read();
} while (!isSpaceChar(c));
return res * sgn;
}
public int[] nextIntArray(int n) {
int a[] = new int[n];
for (int i = 0; i < n; i++) {
a[i] = nextInt();
}
return a;
}
public String nextLine() {
int c = read();
while (isSpaceChar(c))
c = read();
StringBuilder res = new StringBuilder();
do {
res.appendCodePoint(c);
c = read();
} while (!isEndOfLine(c));
return res.toString();
}
public boolean isSpaceChar(int c) {
return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
}
private boolean isEndOfLine(int c) {
return c == '\n' || c == '\r' || c == -1;
}
}
'algorithm' 카테고리의 다른 글
[BOJ/JAVA] 백준 1027번 : 고층 건물 (0) | 2021.02.22 |
---|---|
[BOJ/JAVA] 백준 1012번 : 유기농 배추 (0) | 2021.02.19 |
[BOJ/JAVA] 백준 17141번 : 연구소 2 (0) | 2021.02.17 |
[BOJ/JAVA] 백준 2096번 : 내려가기 (0) | 2021.02.16 |
[BOJ/JAVA] 백준 1987번 : 알파벳 (0) | 2021.02.10 |