Matrix Land


Problem Statement :


You are playing a matrix-based game with the following setup and rules:

You are given a matrix A with n rows and m columns. Each cell contains some points. When a player passes a cell their score increases by the number written in that cell and the number in the cell becomes 0. (If the cell number is positive their score increases, otherwise it decreases.)
The player starts from any cell in the first row and can move left, right or down.
The game is over when the player reaches the last row and stops moving.
image
Print the maximum score that the player can get.

Input Format

The first line contains n and m. The next n lines contain m numbers each, jth number in ith line denotes the number that is written on cell Aij.

Constraints

1 <= n*m <= 4*10^6
-250 <= Aij <= 250



Solution :



title-img


                            Solution in C :

In C++ : 





#include<cstdio>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib> 
#include<vector>
#include<map>
#include<cstring>
#define rep(i,j,k) for(register int i = j; i <= k; ++i)
#define dow(i,j,k) for(register int i = j; i >= k; --i)
#define ll long long
#define mp make_pair
#define fi first
#define se second 
#define all(x) x.begin(),x.end()
#define pb push_back
using namespace std;
 
inline int read() { 
    int s = 0, t = 1; char c = getchar();
    while( !isdigit(c) ) { if( c == '-' ) t = -1; c = getchar(); }
    while( isdigit(c) ) s = s * 10 + c - 48, c = getchar();
    return s * t;
}

const int N = 4e6+5, inf = 1e9+7;
int n, m, maxl, now, pre, f[2][N], v[N], g[N], h[N], sum[N]; 

int main() {
	n = read(), m = read(), now = 0, pre = 1;
	rep(i,1,n) { 
		swap(now,pre); 
		rep(j,1,m) v[j] = read();
		rep(j,1,m) sum[j] = sum[j-1] + v[j];
		rep(j,1,m) g[j] = max(g[j-1]+v[j],0);
		dow(j,m,1) h[j] = max(h[j+1]+v[j],0);
		maxl = -inf;
		rep(j,1,m) { 
			maxl = max(maxl,f[pre][j]-sum[j-1]+g[j-1]);
			f[now][j] = maxl+sum[j]+h[j+1];
		} 
		maxl = -inf;
		dow(j,m,1) { 
			maxl = max(maxl,f[pre][j]+sum[j]+h[j+1]);
			f[now][j] = max(f[now][j],maxl-sum[j-1]+g[j-1]);
		}
	}
	int ans = 0;
	rep(i,1,m) ans = max(ans,f[now][i]);
	cout<<ans<<endl;
	return 0;
}








In Java :





import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int m = in.nextInt();
        int[] a = new int[m];
        long[] left = new long[m];
        long[] right = new long[m];
        long[] prev = new long[m];
        long[] current = new long[m];
        long[] leftplus = new long[m];
        long[] rightplus = new long[m];
                
        for(int A_i = 0; A_i < n; A_i++){
            for(int A_j = 0; A_j < m; A_j++){
                a[A_j] = in.nextInt();
            }
            
            for (int i = 1; i < m; i++)
            {
                left[i] = Math.max(left[i - 1] + a[i - 1], 0);
            }
            
            for (int i = m - 2; i >= 0; i--)
            {
                right[i] = Math.max(right[i + 1] + a[i + 1], 0);
            }
            
            leftplus[0] = prev[0] + a[0];
            
            for (int i = 1; i < m; i++)
            {
                leftplus[i] = Math.max(prev[i] + a[i] + left[i], leftplus[i - 1] + a[i]);
            }
            
            rightplus[m - 1] = prev[m - 1] + a[m - 1];
            
            for (int i = m - 2; i >= 0; i--)
            {
                rightplus[i] = Math.max(prev[i] + a[i] + right[i], rightplus[i + 1] + a[i]);
            }
            
            for (int i = 0; i < m; i++)
            {
                current[i] = Math.max(leftplus[i] + right[i], rightplus[i] + left[i]);
            }
            
            long[] temp = current;
            current = prev;
            prev = temp;
        }
        
        long result = Long.MIN_VALUE;
        
        for (int i = 0; i < m; i++)
        {
            result = Math.max(prev[i], result);
        }
        
        System.out.println(result);
        in.close();
    }
}








In C :





#include <stdio.h>
#include <stdlib.h>
int max(int x,int y);
int N,*table[4000000],*dp,*tdp,*left_sum,*right_sum,*dp_left_tree;

int main(){
  int n,m,ma,total,i,j;
  scanf("%d%d",&n,&m);
  dp=(int*)malloc(m*sizeof(int));
  tdp=(int*)malloc(m*sizeof(int));
  left_sum=(int*)malloc(m*sizeof(int));
  right_sum=(int*)malloc(m*sizeof(int));
  dp_left_tree=(int*)malloc(m*sizeof(int));
  for(i=0;i<n;i++)
    table[i]=(int*)malloc(m*sizeof(int));
  for(i=0;i<n;i++)
    for(j=0;j<m;j++)
      scanf("%d",&table[i][j]);
  for(i=0;i<n;i++){
    for(j=total=0;j<m;j++){
      if(j)
        left_sum[j]=table[i][j]+left_sum[j-1];
      else
        left_sum[j]=table[i][j];
      total+=table[i][j];
    }
    for(j=m-1;j>=0;j--)
      if(j!=m-1)
        right_sum[j]=table[i][j]+right_sum[j+1];
      else
        right_sum[j]=table[i][j];
    for(j=m-2;j>=0;j--)
      left_sum[j]=max(left_sum[j],left_sum[j+1]);
    for(j=1;j<m;j++)
      right_sum[j]=max(right_sum[j],right_sum[j-1]);
    if(i){
      for(j=0;j<m;j++)
        dp_left_tree[j]=dp[j]+left_sum[j];
      for(j=m-2;j>=0;j--)
        dp_left_tree[j]=max(dp_left_tree[j],dp_left_tree[j+1]);
      for(j=0;j<m;j++)
        tdp[j]=right_sum[j]+dp_left_tree[j]-total;
      for(j=0;j<m;j++)
        dp_left_tree[j]=dp[j]+right_sum[j];
      for(j=1;j<m;j++)
        dp_left_tree[j]=max(dp_left_tree[j],dp_left_tree[j-1]);
      for(j=0;j<m;j++){
        if(left_sum[j]+dp_left_tree[j]-total>tdp[j])
          tdp[j]=left_sum[j]+dp_left_tree[j]-total;
      }
      for(j=0;j<m;j++)
        dp[j]=tdp[j];
    }
    else
      for(j=0;j<m;j++)
        dp[j]=left_sum[j]+right_sum[j]-total;
  }
  for(i=0,ma=-1000000001;i<m;i++)
    if(dp[i]>ma)
      ma=dp[i];
  printf("%d",ma);
  return 0;
}
int max(int x,int y){
  return (x>y)?x:y;
}
                        








View More Similar Problems

Costly Intervals

Given an array, your goal is to find, for each element, the largest subarray containing it whose cost is at least k. Specifically, let A = [A1, A2, . . . , An ] be an array of length n, and let be the subarray from index l to index r. Also, Let MAX( l, r ) be the largest number in Al. . . r. Let MIN( l, r ) be the smallest number in Al . . .r . Let OR( l , r ) be the bitwise OR of the

View Solution →

The Strange Function

One of the most important skills a programmer needs to learn early on is the ability to pose a problem in an abstract way. This skill is important not just for researchers but also in applied fields like software engineering and web development. You are able to solve most of a problem, except for one last subproblem, which you have posed in an abstract way as follows: Given an array consisting

View Solution →

Self-Driving Bus

Treeland is a country with n cities and n - 1 roads. There is exactly one path between any two cities. The ruler of Treeland wants to implement a self-driving bus system and asks tree-loving Alex to plan the bus routes. Alex decides that each route must contain a subset of connected cities; a subset of cities is connected if the following two conditions are true: There is a path between ever

View Solution →

Unique Colors

You are given an unrooted tree of n nodes numbered from 1 to n . Each node i has a color, ci. Let d( i , j ) be the number of different colors in the path between node i and node j. For each node i, calculate the value of sum, defined as follows: Your task is to print the value of sumi for each node 1 <= i <= n. Input Format The first line contains a single integer, n, denoti

View Solution →

Fibonacci Numbers Tree

Shashank loves trees and math. He has a rooted tree, T , consisting of N nodes uniquely labeled with integers in the inclusive range [1 , N ]. The node labeled as 1 is the root node of tree , and each node in is associated with some positive integer value (all values are initially ). Let's define Fk as the Kth Fibonacci number. Shashank wants to perform 22 types of operations over his tree, T

View Solution →

Pair Sums

Given an array, we define its value to be the value obtained by following these instructions: Write down all pairs of numbers from this array. Compute the product of each pair. Find the sum of all the products. For example, for a given array, for a given array [7,2 ,-1 ,2 ] Note that ( 7 , 2 ) is listed twice, one for each occurrence of 2. Given an array of integers, find the largest v

View Solution →