Advertisement
Mirbek

Maximum Sum with number of ways

Dec 22nd, 2021
1,210
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.37 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. const int N = 205;
  6.  
  7. int n, m;
  8. long long a[N][N], dp[N][N], cnt[N][N];
  9.  
  10. int main(){
  11.     cin >> n >> m;
  12.  
  13.     for (int i = 1; i <= n; i++) {
  14.         for (int j = 1; j <= m; j++) {
  15.             cin >> a[i][j];
  16.         }
  17.     }
  18.  
  19.     for (int i = 1; i <= m; i++) {
  20.         dp[1][i] = a[1][i];
  21.         cnt[1][i] = 1;
  22.     }
  23.  
  24.     for (int i = 2; i <= n; i++) {
  25.         for (int j = 1; j <= m; j++) {
  26.             int mx = dp[i - 1][j];
  27.             if (j - 1 >= 1 && mx < dp[i - 1][j - 1]) {
  28.                 mx = dp[i - 1][j - 1];
  29.             }
  30.             if (j + 1 <= m && mx < dp[i - 1][j + 1]) {
  31.                 mx = dp[i - 1][j + 1];
  32.             }
  33.  
  34.             dp[i][j] = mx + a[i][j];
  35.             if (j - 1 >= 1 && dp[i - 1][j - 1] == mx) {
  36.                 cnt[i][j] += cnt[i - 1][j - 1];
  37.             }
  38.             if (dp[i - 1][j] == mx) {
  39.                 cnt[i][j] += cnt[i - 1][j];
  40.             }
  41.             if (j + 1 <= m && dp[i - 1][j + 1] == mx) {
  42.                 cnt[i][j] += cnt[i - 1][j + 1];
  43.             }
  44.         }
  45.     }
  46.  
  47.     long long mx = dp[n][1];
  48.  
  49.     for (int i = 2; i <= m; i++) {
  50.         mx = max(mx, dp[n][i]);
  51.     }
  52.  
  53.     cout << mx << " ";
  54.  
  55.     long long cn = 0;
  56.  
  57.     for (int i = 1; i <= m; i++) {
  58.         if (dp[n][i] == mx) cn += cnt[n][i];
  59.     }
  60.  
  61.     cout << cn << endl;
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement