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 :



title-img


                            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));
    scanf("%d",&t);
    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) * (cur_point.data % mod);
                       seg_count[0]++;
                       break;
                case 0:
                       answer+= (seg_count[0] % mod) * (cur_point.data % mod);
                       seg_count[1]++;
                       break;
            }
            answer = answer % mod;
        }
        printf("%llu\n", answer);
        free(points);
    }
    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;
	cin>>T;
	for(;T--;)
	{
		int M,N,cost;
		cin>>M>>N;
		vector<pair<char,unsigned long long> > cutCost;
		for (int i = 0; i < M-1; ++i)
		{
			cin>>cost;
			cutCost.push_back(make_pair('y',cost));
		}
		for (int i = 0; i < N-1; ++i)
		{
			cin>>cost;
			cutCost.push_back(make_pair('x',cost));
		}
		sort(cutCost.begin(),cutCost.end(),compare);

		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;
				++hcut;
			}
			else if(cutCost[i].first == 'x')
			{
				totalcost = (totalcost + ((hcut*cutCost[i].second)%1000000007))%1000000007;
				++vcut;
			}
		}
		cout<<totalcost<<"\n";
	}   
    return 0;
}
                    


                        Solution in Java :

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 sc = new Scanner(new BufferedInputStream(System.in));
        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();
            }
            Arrays.sort(yi,Collections.reverseOrder());
            Arrays.sort(xi,Collections.reverseOrder());
            
            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;
                    ny++;
                } else if(nx<n && (ny>=m || xi[nx-1]>=yi[ny-1])) {
                    c= (c + ((long)ny*(long)xi[nx-1])%1000000007)%1000000007;
                    nx++;
                }
            }
            
            System.out.println(c);
        }
    }
}
                    


                        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
        else:
            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

QHEAP1

This question is designed to help you get a better understanding of basic heap operations. You will be given queries of types: " 1 v " - Add an element to the heap. " 2 v " - Delete the element from the heap. "3" - Print the minimum of all the elements in the heap. NOTE: It is guaranteed that the element to be deleted will be there in the heap. Also, at any instant, only distinct element

View Solution →

Jesse and Cookies

Jesse loves cookies. He wants the sweetness of all his cookies to be greater than value K. To do this, Jesse repeatedly mixes two cookies with the least sweetness. He creates a special combined cookie with: sweetness Least sweet cookie 2nd least sweet cookie). He repeats this procedure until all the cookies in his collection have a sweetness > = K. You are given Jesse's cookies. Print t

View Solution →

Find the Running Median

The median of a set of integers is the midpoint value of the data set for which an equal number of integers are less than and greater than the value. To find the median, you must first sort your set of integers in non-decreasing order, then: If your set contains an odd number of elements, the median is the middle element of the sorted sample. In the sorted set { 1, 2, 3 } , 2 is the median.

View Solution →

Minimum Average Waiting Time

Tieu owns a pizza restaurant and he manages it in his own way. While in a normal restaurant, a customer is served by following the first-come, first-served rule, Tieu simply minimizes the average waiting time of his customers. So he gets to decide who is served first, regardless of how sooner or later a person comes. Different kinds of pizzas take different amounts of time to cook. Also, once h

View Solution →

Merging Communities

People connect with each other in a social network. A connection between Person I and Person J is represented as . When two persons belonging to different communities connect, the net effect is the merger of both communities which I and J belongs to. At the beginning, there are N people representing N communities. Suppose person 1 and 2 connected and later 2 and 3 connected, then ,1 , 2 and 3 w

View Solution →

Components in a graph

There are 2 * N nodes in an undirected graph, and a number of edges connecting some nodes. In each edge, the first value will be between 1 and N, inclusive. The second node will be between N + 1 and , 2 * N inclusive. Given a list of edges, determine the size of the smallest and largest connected components that have or more nodes. A node can have any number of connections. The highest node valu

View Solution →