Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <bits/stdc++.h>
- using namespace std;
- int n, m;
- int mat[55][55];
- int dp[55][55];
- pair<int, int> path[55][55];
- int rec(int i, int j) {
- if(i == n - 1 and j == m - 1) {
- path[i][j] = make_pair(-1, -1);
- return mat[i][j];
- }
- if(dp[i][j] != -1) {
- return dp[i][j];
- }
- int right_path = 0, down_path = 0;
- if(i + 1 < n) {
- down_path = rec(i + 1, j) + mat[i][j];
- }
- if(j + 1 < m) {
- right_path = rec(i, j + 1) + mat[i][j];
- }
- if(down_path > right_path) {
- path[i][j] = make_pair(i + 1, j);
- }
- else {
- path[i][j] = make_pair(i, j + 1);
- }
- return dp[i][j] = max(down_path, right_path);
- }
- int main() {
- cin >> n >> m;
- for(int i = 0; i < n; i++) {
- for(int j = 0; j < m; j++) {
- cin >> mat[i][j];
- }
- }
- memset(dp, -1, sizeof dp);
- cout << rec(0, 0) << endl;
- pair<int, int> at;
- for(at = make_pair(0, 0); at != make_pair(-1, -1); at = make_pair(path[at.first][at.second].first, path[at.first][at.second].second)) {
- cout << at.first + 1 << " " << at.second + 1<< endl;
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement