Problem link: 1004 - Monkey Banana Problem
N.B: This is an iterative DP solution. Please try at least 1 hour yourself before seeing other's solution. Happy coding!
- #include <bits/stdc++.h>
- using namespace std;
- int main() {
- int cs;
- cin >> cs;
- for(int t = 1; t <= cs; t++) {
- int n;
- cin >> n;
- long long int arr[205][105] = {0}, sum[205][105] = {0};
- for(int i = 1; i <= n; i++) {
- for(int j = 1; j <= i; j++)
- cin >> arr[i][j];
- }
- int r = n;
- for(int i = n + 1; i <= 2 * n - 1; i++) {
- for(int j = 1; j <= r - 1; j++)
- cin >> arr[i][j];
- r--;
- }
- sum[1][1] = arr[1][1];
- for(int i = 2; i <= n; i++) {
- for(int j = 1; j <= i; j++) {
- if(j == 1) sum[i][j] = sum[i - 1][j] + arr[i][j];
- if(j == i) sum[i][j] = sum[i - 1][j - 1] + arr[i][j];
- else sum[i][j] = max(sum[i - 1][j - 1], sum[i - 1][j]) + arr[i][j];
- }
- }
- int s = n;
- for(int i = n + 1; i <= 2 * n - 1; i++) {
- for(int j = 1; j <= s - 1; j++)
- sum[i][j] = max(sum[i - 1][j], sum[i - 1][j + 1]) + arr[i][j];
- s--;
- }
- cout << "Case " << t << ": " << sum[2 * n - 1][1] << endl;
- }
- return 0;
- }
No comments:
Post a Comment