PAT 2-09. 装箱问题模拟(20)

题目链接 :http://www.patest.cn/contests/ds/2-09

解题思路:直接模拟, 记录已经使用的箱子的剩余容量, 如果已经使用的箱子中没有可以放下物品的箱子, 在增加另一个箱子. 最坏情况下N的箱子都要使用, 不会有N个箱子都不够用的情况(i.e. 其中si为满足1<= si<=100的整数).

代码如下(有注释):

#include<iostream>
using namespace std;

int leave[1005];//记录每个箱子的剩余量,初始为100(最多有1000个箱子) 

int main()
{
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
	{
		leave[i]=100;
	}
	int temp,cnt=1,flag;
	cin>>temp;
	leave[1]-=temp;
	cout<<temp<<" "<<1<<endl;
	for(int i=2;i<=n;i++)
	{
		flag=1;//flag记录是否需要增加箱子,初始时假设需要增加 
		cin>>temp;
		for(int j=1;j<=cnt;j++)
		{
			if(leave[j]>=temp)
			{
				leave[j]-=temp;
				cout<<temp<<" "<<j<<endl;
				flag=0;
				break;
			}
		}
		if(flag)//如果需要增加 
		{
			cnt++;
			leave[cnt]-=temp;
			cout<<temp<<" "<<cnt<<endl;
		}
	}
	cout<<cnt<<endl;
	return 0;
}

  

posted @ 2015-03-10 21:19  职场亮哥  阅读(374)  评论(0编辑  收藏  举报