Cutting Boards

Problem Statement :

Alice gives Bob a board composed of  wooden squares and asks him to find the minimum cost of breaking the board back down into its individual squares. To break the board down, Bob must make cuts along its horizontal and vertical lines.

To reduce the board to squares, Bob makes horizontal and vertical cuts across the entire board. Each cut has a given cost,  or  for each cut along a row or column across one board, so the cost of a cut must be multiplied by the number of segments it crosses. The cost of cutting the whole board down into  squares is the sum of the costs of each successive cut.

Can you help Bob find the minimum cost? The number may be large, so print the value modulo .

For example, you start with a  board. There are two cuts to be made at a cost of  for the horizontal and  for the vertical. Your first cut is across  piece, the whole board. You choose to make the horizontal cut between rows  and  for a cost of . The second cuts are vertical through the two smaller boards created in step  between columns  and . Their cost is . The total cost is  and .

Function Description

Complete the boardCutting function in the editor below. It should return an integer.

boardCutting has the following parameter(s):

cost_x: an array of integers, the costs of vertical cuts
cost_y: an array of integers, the costs of horizontal cut

Input Format

The first line contains an integer , the number of queries.

The following  sets of lines are as follows:

The first line has two positive space-separated integers  and , the number of rows and columns in the board.
The second line contains  space-separated integers cost_y[i], the cost of a horizontal cut between rows  and  of one board.
The third line contains  space-separated integers cost_x[j], the cost of a vertical cut between columns  and  of one board.

Solution :


                            Solution in C :

In  C  :

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

#define LLU unsigned long long int

typedef struct {
    LLU data;
    int side;
} point;

int my_compare(const void *i1, const void *i2)
    point *p1 = (point *)i1;
    point *p2 = (point *)i2;
    if(p1->data > p2->data) return -1;
    else return 1;
int main() {

    int t;
    LLU answer=0, seg_count[2], m, n, i;
    LLU mod = (LLU)pow(10, 9) + 7;
    point *points, cur_point;
    //printf("mod=%llu %d %d\n", mod, sizeof(int), sizeof(LLU));
    while(t--) {
        scanf("%llu %llu", &m, &n);
        answer = 0;
        seg_count[0] =1;
        seg_count[1] =1;
        points = (point *)malloc(sizeof(point)*(m+n-2));
        for(i=0;i<m-1;i++) {
            scanf("%llu", &points[i].data);
            points[i].side = 1;
        for(i=0;i<n-1;i++) {
            scanf("%llu", &points[i+m-1].data);
            points[i+m-1].side = 0;
        qsort(points, m+n-2, sizeof(point), my_compare);
        for(i=0;i<m+n-2;i++) {
            cur_point = points[i];
            switch(cur_point.side) {
                case 1:
                       answer+= (seg_count[1] % mod) * ( % mod);
                case 0:
                       answer+= (seg_count[0] % mod) * ( % mod);
            answer = answer % mod;
        printf("%llu\n", answer);
    return 0;

                        Solution in C++ :

In  C++  :

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

bool compare(pair<char,unsigned long long> A,pair<char,unsigned long long> B)
	return A.second > B.second;

int main()
	int T;
		int M,N,cost;
		vector<pair<char,unsigned long long> > cutCost;
		for (int i = 0; i < M-1; ++i)
		for (int i = 0; i < N-1; ++i)

		unsigned long long vcut = 1, hcut = 1, totalcost = 0;

		for (int i = 0; i < cutCost.size(); ++i)
			if(cutCost[i].first == 'y')
				totalcost = (totalcost + ((vcut*cutCost[i].second)%1000000007))%1000000007;
			else if(cutCost[i].first == 'x')
				totalcost = (totalcost + ((hcut*cutCost[i].second)%1000000007))%1000000007;
    return 0;

                        Solution in Java :

In  Java :

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

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(new BufferedInputStream(;
        int t = sc.nextInt();

        for (int i = 0; i < t; i++) {
            int m = sc.nextInt();
            int n = sc.nextInt();
            Integer[] yi = new Integer[m-1];
            Integer[] xi = new Integer[n-1];
            for(int j=0;j<m-1;j++){
                yi[j]= sc.nextInt();
            for(int j=0;j<n-1;j++){
                xi[j]= sc.nextInt();
            int ny=1,nx=1;
            long c=0;
            while(ny<m || nx<n) {
                if(ny<m && (nx>=n || yi[ny-1]>xi[nx-1])) {
                    c= (c + ((long)nx*(long)yi[ny-1])%1000000007)%1000000007;
                } else if(nx<n && (ny>=m || xi[nx-1]>=yi[ny-1])) {
                    c= (c + ((long)ny*(long)xi[nx-1])%1000000007)%1000000007;

                        Solution in Python : 
In   Python3 :

for t in range(int(input())):
    m,n = map(int,input().split())
    hor = sorted(map(int,input().split()),reverse=True)
    ver = sorted(map(int,input().split()),reverse=True)
    h = v = 0
    ret = 0
    modulo = 10**9 + 7
    for i in range(m+n):
        if h>=len(hor) or v>=len(ver): break
        if ver[v] > hor[h] :
            ret += ((h+1)*ver[v])%modulo
            v += 1
            ret += (hor[h] *(v+1)) % modulo
            h += 1
    if h<len(hor):
        ret += (sum(hor[h:])*(v+1)) % modulo
    elif v<len(ver):
        ret += (sum(ver[v:])*(h+1)) % modulo
    print(ret% modulo)

View More Similar Problems

2D Array-DS

Given a 6*6 2D Array, arr: 1 1 1 0 0 0 0 1 0 0 0 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 An hourglass in A is a subset of values with indices falling in this pattern in arr's graphical representation: a b c d e f g There are 16 hourglasses in arr. An hourglass sum is the sum of an hourglass' values. Calculate the hourglass sum for every hourglass in arr, then print t

View Solution →

Dynamic Array

Create a list, seqList, of n empty sequences, where each sequence is indexed from 0 to n-1. The elements within each of the n sequences also use 0-indexing. Create an integer, lastAnswer, and initialize it to 0. There are 2 types of queries that can be performed on the list of sequences: 1. Query: 1 x y a. Find the sequence, seq, at index ((x xor lastAnswer)%n) in seqList.

View Solution →

Left Rotation

A left rotation operation on an array of size n shifts each of the array's elements 1 unit to the left. Given an integer, d, rotate the array that many steps left and return the result. Example: d=2 arr=[1,2,3,4,5] After 2 rotations, arr'=[3,4,5,1,2]. Function Description: Complete the rotateLeft function in the editor below. rotateLeft has the following parameters: 1. int d

View Solution →

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →