Friday, July 4, 2008

Top Coder SRM 370 Div 2 250

Problem Statement

There are several empty containers lined up in a row, and you want to put packages into them. You start with the first container and the first package. Do the following until all the packages are inside containers:

If the current package cannot fit into the current container, skip to step 3. Otherwise, go to the next step.
Put the current package into the current container. Grab the next package, and go back to step 1.
Put the current container aside (you will not put any more packages into that container). Move on to the next container in line, and go back to step 1.

You are given a int[] containers, the i-th element of which is the capacity of the i-th container in line, and a int[] packages, the i-th element of which is the size of the i-th package. The constraints will guarantee that you will be able to put all the packages into containers using the above procedure. Return the sum of the wasted space in all the containers. The wasted space in a container is its capacity minus the total size of its contents.

Definition

Class:
Containers

Method:
wastedSpace

Parameters:
int[], int[]

Returns:
int

Method signature:
int wastedSpace(int[] containers, int[] packages)

(be sure your method is public)

Notes

-
A set of packages fits into a container if the total size of all the packages in the set does not exceed the capacity of the container.

-
You must use the containers and the packages in the order that they are given. You may not reorder them.

Constraints

-
containers will contain between 1 and 50 elements, inclusive.

-
Each element of containers will be between 1 and 1000, inclusive.

-
packages will contain between 1 and 50 elements, inclusive.

-
Each element of packages will be between 1 and 1000, inclusive.

-
It will be possible to put all the packages inside containers using the method described in the statement.

Examples

{ 3, 4, 5, 6 }

{ 3, 3, 3, 3, 3 }
Returns: 3

This problem statement is the exclusive and proprietary property of TopCoder, Inc. Any unauthorized use or reproduction of this information without the prior written consent of TopCoder, Inc. is strictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.

public class Containers {
    public int wastedSpace(int[] a, int[] b){
        int w=0,i,j;
        
        for(i=0,j=0;j<b.length;){
            if(a[i]>=b[j]){
                a[i]-=b[j];
                j++;
            }else {
                w+=(i==0?0:a[i]);
                i++;
            }
        }
        return w;
    }
}
blog comments powered by Disqus

Labels