Zhejiang version of "C language programming experimental guidance and exercises (3rd Edition)" experimental 7-1-13 title set packing problem (20 points)

topic:

Suppose there are N items of goods, respectively, the size s1, s 2, ..., s i, ..., s N, where si is an integer satisfying 1≤s i≤100. Put these items into a group of a capacity of the box 100 (No. 1-N) are. Packing method: for each item, the box-sequential scanning, sufficient to put the article into its first accommodate boxes. Writing a program that simulate this packing process, and outputs the serial number of each article of the box is located, and placing all the items required for the number of boxes.

Input formats:

Input of the first line gives the number of N items (≤1000); a second line gives the N positive integers si (1≤s i ≤100, represents the size of the article item i).

Output formats:

Input and output in the order of the size of each box where the number of items, each item representing one line, the last line of output desired number of boxes.

Sample input:

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

Ideas:

a [1000] digital test
b [1000] is the number of boxes, each box represents the initial value 0 is initially placed in the article number 0
if the value of the test article a [i] + b [j ]> 100 denotes box means less than, j ++ replaced boxes
If a [i] + b [j ] <= 100 then the box also mounted, put the test data a [i] is added boxes b [j]

Code:

#include<stdio.h>
int main()
{
	int	a[1000],b[1000]={0};
	int n,i,j,flag,c=0;
	scanf("%d",&n);
	for(i=0;i<n;i++)
		scanf("%d",&a[i]);//每个物品大小
	
	for(i=0;i<n;i++)
	{
		flag=0;
		j=0;
		while(flag==0)
		{
			if(a[i]+b[j]<=100)
			{
				b[j]+=a[i];
				flag=1;
				printf("%d %d\n",a[i],j+1);//序号从1开始
			}
			else if(a[i]+b[j]>100)
				j++;
		}
	}
	for(j=0;j<n;j++)//统计占据箱子数
	{
		if(b[j]!=0)
			c++;
		else
			break;
	}
	printf("%d",c);
	return 0;
}
Published 22 original articles · won praise 4 · Views 860

Guess you like

Origin blog.csdn.net/qq_43745026/article/details/104918902