Equal Stacks


Problem Statement :


ou have three stacks of cylinders where each cylinder has the same diameter, but they may vary in height. You can change the height of a stack by removing and discarding its topmost cylinder any number of times.

Find the maximum possible height of the stacks such that all of the stacks are exactly the same height. This means you must remove zero or more cylinders from the top of zero or more of the three stacks until they are all the same height, then return the height.

Example


h1  =  [ 1,  2, 1, 1 ]
h2  =  [ 1, 1, 2 ]
h3  = [ 1, 1 ]



There are 4, 3 and 2  cylinders in the three stacks, with their heights in the three arrays. Remove the top 2 cylinders from h1 (heights = [1, 2]) and from h2 (heights = [1, 1]) so that the three stacks all are 2 units tall. Return 2 as the answer.

Input Format

The first line contains three space-separated integers,  n1 ,  n2 , and n3, the numbers of cylinders in stacks 1 , 2 , and 3. The subsequent lines describe the respective heights of each cylinder in a stack from top to bottom:

The second line contains n1 space-separated integers, the cylinder heights in stack . The first element is the top cylinder of the stack.
The third line contains n2 space-separated integers, the cylinder heights in stack . The first element is the top cylinder of the stack.
The fourth line contains n3 space-separated integers, the cylinder heights in stack . The first element is the top cylinder of the stack.

Note: An empty stack is still a stack.

Function Description

Complete the equalStacks function in the editor below.

equalStacks has the following parameters:

int h1[n1]: the first array of heights
int h2[n2]: the second array of heights
int h3[n3]: the third array of heights
Returns

int: the height of the stacks when they are equalized



Solution :



title-img


                            Solution in C :

In C++ :




#include<bits/stdc++.h>
using namespace std;
#define FOR(i,a,b) for(int i = (a); i <= (b); ++i)
#define FORD(i,a,b) for(int i = (a); i >= (b); --i)
#define RI(i,n) FOR(i,1,(n))
#define REP(i,n) FOR(i,0,(n)-1)
#define mini(a,b) a=min(a,b)
#define maxi(a,b) a=max(a,b)
#define mp make_pair
#define pb push_back
#define st first
#define nd second
#define sz(w) (int) w.size()
typedef vector<int> vi;
typedef long long ll;
typedef long double ld;
typedef pair<int,int> pii;
const int inf = 1e9 + 5;
const int nax = 1e6 + 5;



int main() {
	int aa, bb, cc;
	scanf("%d%d%d", &aa, &bb, &cc);
	vi a, b, c;
	REP(_, aa) {
		int x;
		scanf("%d", &x);
		a.pb(x);
	}
	REP(_, bb) {
		int x;
		scanf("%d", &x);
		b.pb(x);
	}
	REP(_, cc) {
		int x;
		scanf("%d", &x);
		c.pb(x);
	}
	reverse(a.begin(), a.end());
	reverse(b.begin(), b.end());
	reverse(c.begin(), c.end());
	ll A = 0, B = 0, C = 0;
	for(int x : a) A += x;
	for(int x : b) B += x;
	for(int x : c) C += x;
	while(A != B || A != C) {
		if(A == max(max(A, B), C)) {
			A -= a.back();
			a.pop_back();
		}
		else if(B == max(max(A, B), C)) {
			B -= b.back();
			b.pop_back();
		}
		else {
			C -= c.back();
			c.pop_back();
		}
	}
	printf("%lld\n", A);
	return 0;
}









In Java :




/* Andy Rock
 * June 25, 2016
 * 
 * World CodeSprint #4
 */

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

public class Main
{
	public static void main(String[] args) throws IOException
	{
		BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

		StringTokenizer st = new StringTokenizer(in.readLine());
		int[] n =
		{
			Integer.parseInt(st.nextToken()),
			Integer.parseInt(st.nextToken()),
			Integer.parseInt(st.nextToken())
		};

		int[][] h = new int[3][];
		int[] sum = new int[3];
		for(int i=0;i<3;i++)
		{
			st = new StringTokenizer(in.readLine());
			h[i] = new int[n[i]];
			for(int j=0;j<n[i];j++)
			{
				h[i][j] = Integer.parseInt(st.nextToken());
				sum[i] += h[i][j];
			}
		}

		int[] pos = new int[3];
		while(true)
		{
			for(int i=0;i<3;i++)
				if(sum[i] > Math.min(sum[0], Math.min(sum[1], sum[2])))
				{
					sum[i] -= h[i][pos[i]];
					pos[i]++;
				}
			if(sum[0] == sum[1] && sum[1] == sum[2])
				break;
		}

		System.out.println(sum[0]);
	}
}








In C :




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

int main() {
    int n1,n2,n3,i,j=0,k=0,s1=0,s2=0,s3=0;
    scanf("%d %d %d",&n1,&n2,&n3);
    int arr1[n1];
    int arr2[n2];
    int arr3[n3];
    for(i=0;i<n1;i++){
        scanf("%d",&arr1[i]);
        s1+=arr1[i];
    }
    for(i=0;i<n2;i++){
        scanf("%d",&arr2[i]);
        s2+=arr2[i];
    }
    for(i=0;i<n3;i++){
        scanf("%d",&arr3[i]);
        s3+=arr3[i];
    }
    i=0;
    while(1){
        if((s1==s2 && s2==s3) || s1==0 || s2==0 || s3==0)
            break;
        if(s1>=s2 && s1>=s3)
            s1-=arr1[i++];
        else if(s2>=s1 && s2>=s3)
            s2-=arr2[j++];
        else
            s3-=arr3[k++];
    }
    if(s1==0 || s2==0 || s3==0)
        printf("0");
    else
        printf("%d",s1);
    return 0;
}









In Python3 :





def read_stack():
    stack = [int(x) for x in input().split(' ')]
    stack = list(reversed(stack))
    sum_stack = set()
    psum = 0
    for i in range(len(stack)):
        psum += stack[i]
        sum_stack.add(psum)
    return sum_stack

input()

ans = read_stack()
ans &= read_stack()
ans &= read_stack()
if len(ans) > 0:
    print(max(ans))
else:
    print(0)
                        








View More Similar Problems

Queue using Two Stacks

A queue is an abstract data type that maintains the order in which elements were added to it, allowing the oldest elements to be removed from the front and new elements to be added to the rear. This is called a First-In-First-Out (FIFO) data structure because the first element added to the queue (i.e., the one that has been waiting the longest) is always the first one to be removed. A basic que

View Solution →

Castle on the Grid

You are given a square grid with some cells open (.) and some blocked (X). Your playing piece can move along any row or column until it reaches the edge of the grid or a blocked cell. Given a grid, a start and a goal, determine the minmum number of moves to get to the goal. Function Description Complete the minimumMoves function in the editor. minimumMoves has the following parameter(s):

View Solution →

Down to Zero II

You are given Q queries. Each query consists of a single number N. You can perform any of the 2 operations N on in each move: 1: If we take 2 integers a and b where , N = a * b , then we can change N = max( a, b ) 2: Decrease the value of N by 1. Determine the minimum number of moves required to reduce the value of N to 0. Input Format The first line contains the integer Q.

View Solution →

Truck Tour

Suppose there is a circle. There are N petrol pumps on that circle. Petrol pumps are numbered 0 to (N-1) (both inclusive). You have two pieces of information corresponding to each of the petrol pump: (1) the amount of petrol that particular petrol pump will give, and (2) the distance from that petrol pump to the next petrol pump. Initially, you have a tank of infinite capacity carrying no petr

View Solution →

Queries with Fixed Length

Consider an -integer sequence, . We perform a query on by using an integer, , to calculate the result of the following expression: In other words, if we let , then you need to calculate . Given and queries, return a list of answers to each query. Example The first query uses all of the subarrays of length : . The maxima of the subarrays are . The minimum of these is . The secon

View Solution →

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 →