https://www.acmicpc.net/problem/9465
틀린 코드 :
#include<iostream>
#include<cstring>
using namespace std;
int T;
int n;
int s[2][100001];
int dp[2][100001];
int main() {
cin >> T;
while (T--) {
memset(dp, 0, sizeof(dp));
memset(s, 0, sizeof(s));
cin >> n;
for (int i = 0; i < 2; i++) {
for (int j = 0; j < n; j++) {
cin >> s[i][j];
}
}
dp[0][0] = s[0][0];
dp[1][0] = s[1][0];
dp[0][1] = dp[1][0] + s[0][1];
dp[1][1] = dp[0][0] + s[1][1];
dp[0][2] = max(dp[1][1] + s[0][2], dp[0][0]+s[1][2]);
dp[0][2] = max(dp[0][2], dp[1][0]+s[0][2]);
dp[1][2] = max(dp[0][1] + s[1][2], dp[1][0] + s[0][2]);
dp[1][2] = max(dp[1][2], dp[0][0] + s[1][2]);
int res =max(dp[0][0], dp[1][0]);
res = max(res, dp[1][1]);
res = max(res, dp[0][1]);
res = max(res, dp[1][2]);
res = max(res, dp[0][2]);
for (int i = 3; i < n; i++) {
dp[0][i] = max(dp[1][i-1]+s[0][i], dp[0][i-2]+s[1][i]);
dp[0][i] = max(dp[0][i], dp[1][i-2]+s[0][i]);
dp[1][i] = max(dp[0][i-1] +s[1][i], dp[1][i-2]+s[0][i]);
dp[1][i] = max(dp[1][i], dp[0][i-2]+s[1][i]);
res = max(res, dp[1][n - 1]);
res = max(res, dp[0][n - 1]);
}
cout << res <<endl;
}
return 0;
}
맞은 코드 :
#include <iostream>
#include<cstring>
using namespace std;
int T, N, result = 0;
int arr[2][100001] = { 0, };
int dp[2][100001] = { 0, };
int main() {
cin >> T;
for (int i = 0; i < T; i++) {
result = 0;
memset(dp, 0, sizeof(dp));
memset(arr, 0, sizeof(arr));
cin >> N;
for (int j = 0; j < 2; j++) {
for (int k = 0; k < N; k++) {
cin >> arr[j][k];
}
}
dp[0][0] = arr[0][0];
dp[1][0] = arr[1][0];
dp[0][1] = dp[1][0] + arr[0][1];
dp[1][1] = dp[0][0] + arr[1][1];
result = max(max(dp[0][0], dp[1][0]), max(dp[0][1], dp[1][1]));
for (int j = 2; j < N; j++) {
dp[0][j] = max(dp[1][j - 2] + arr[0][j], max(dp[1][j - 1] + arr[0][j], dp[0][j - 2] + arr[0][j]));
dp[1][j] = max(dp[0][j - 2] + arr[1][j], max(dp[0][j - 1] + arr[1][j], dp[1][j - 2] + arr[1][j]));
result = max(result, max(dp[0][j], dp[1][j]));
}
cout << result << '\n';
}
}
'코딩테스트_백준풀이' 카테고리의 다른 글
2Xn 타일링 #11726 c++ 풀이 (0) | 2023.11.10 |
---|---|
BABBA #9625 c++ 풀이 (0) | 2023.11.10 |
RGB거리 #1149 c++ 풀이 (0) | 2023.11.06 |
N과 M 시리즈 ( 순열, 조합, 중복순열, 중복조합 ) (0) | 2023.11.02 |
A -> B #16953 c++ 풀이 (0) | 2023.11.01 |