Lab 7-1-13 Box Packing Problem (20 points)

Lab 7-1-13 Box Packing Problem (20 points)
Suppose there are N items with sizes s1, s2, ..., si, ..., sN, where si is an integer satisfying 1≤si​si≤100.
These items are to be packed into a batch of 100 boxes (numbered 1-N). The packing method is: for each item, scan the box sequentially,
Put the item in the first chest large enough to hold it. Please write a program to simulate this packing process,
And output the serial number of the box in which each item is located, and the number of boxes required to place all the items.

Input format:
The first line of input gives the number of items N (≤1000); the second line gives N positive integers si (1≤si≤100, indicating the size of the item i).

Output format:
Output the size of each item and its box number in the input order, each item occupies one line, and the last line outputs the required number of boxes.

Input sample:
8
60 70 80 90 30 40 10 20

Sample output:
60 1
70 2
80 3
90 4
30 1
40 5
10 1
20 2
5

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <ctype.h>
#define N 1000
//Time: April 20, 2018 09:57:19
//Idea: The key is to determine which box (container) each array element (item) is placed in? Starting with the 2nd item,
// Loop n-1 times, check whether the sum of the n-1 items and the previous items satisfies the sum of the sum is less than the capacity of the box, if it is less than 100, find the position where it should be placed in the box.
intmain()
{
	int n, i, j, flag, max;
	int s[N]; //input data
	int d[N]; //temporary array (used to dynamically handle items in the chest)
	int pos[N];
	scanf("%d", &n);
	for (i = 0; i<N; i++)
	{
		pos[i] = -1;
	}
	for (i = 0; i<n; i++)
	{
		scanf("%d", &s[i]);
		d[i] = s[i];
	}
	pos[0] = 0; //Initialize the number of the first box to 0
	for (i = 1; i<n; i++)
	{
		for (j = 0; j<i; j++)
		{
			flag = 0; //update flag in second loop
			if (d[i] + d[j] <= 100) //find the same container
			{
				d[j] = d[j] + d[i];
				d[i] = 0;
				pos[i] = j; //Record the number of the container in which the i-th element in d[i] is placed
				flag = 1;
				break;
			}
		}
		if (flag == 0)
		{
			pos[i] = i;
		}
	}
	max = 0;
	for (i = 0; i<n; i++)
	{
		if (pos[i]>max)
		max = pos[i];
	}
	for (i = 0; i<n; i++)
	{
		printf("%d %d\n", s[i], pos[i] + 1);
	}
	printf("%d\n", max + 1);
 	return 0;
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326708504&siteId=291194637