Minimize cost of placing tiles of dimensions 2 * 1 over a Matrix | C ++ program for the above approach ; Function to find the minimum cost in placing N tiles in a grid M [ ] [ ] ; Stores the minimum profit after placing i tiles ; Traverse the grid [ ] [ ] ; Update the orig_cost ; Traverse over the range [ 2 , N ] ; Place tiles horizentally or vertically ; Print the answer ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; void tile_placing ( vector < vector < int > > grid , int N ) { int dp [ N + 5 ] = { 0 } ; int orig_cost = 0 ; for ( int i = 0 ; i < 2 ; i ++ ) { for ( int j = 0 ; j < N ; j ++ ) { orig_cost += grid [ i ] [ j ] ; } } dp [ 0 ] = 0 ; dp [ 1 ] = abs ( grid [ 0 ] [ 0 ] - grid [ 1 ] [ 0 ] ) ; for ( int i = 2 ; i <= N ; i ++ ) { dp [ i ] = max ( dp [ i - 1 ] + abs ( grid [ 0 ] [ i - 1 ] - grid [ 1 ] [ i - 1 ] ) , dp [ i - 2 ] + abs ( grid [ 0 ] [ i - 2 ] - grid [ 0 ] [ i - 1 ] ) + abs ( grid [ 1 ] [ i - 2 ] - grid [ 1 ] [ i - 1 ] ) ) ; } cout << orig_cost - dp [ N ] ; } int32_t main ( ) { vector < vector < int > > M = { { 7 , 5 , 1 , 3 } , { 8 , 6 , 0 , 2 } } ; int N = M [ 0 ] . size ( ) ; tile_placing ( M , N ) ; return 0 ; }