【hdoj_2124】RepairTheWall

题目:http://acm.hdu.edu.cn/showproblem.php?pid=2124


思路:贪心法.由于要求所需的块儿(block)的最小数目,先把所有的块儿加起来,看看大小是否>=缝隙L,如果不是,则输出impossible,如果可以,则先用最大的块儿填充,然后用更小的,直到缝隙补齐就停止.


C++代码如下

#include<iostream>
#include<algorithm>
using namespace std;

bool cmp(int a,int b)
{
	return a>b;
}

int main()
{
	int L,N;
	while(cin>>L>>N)
	{
		int *A = new int[N];
		int sum=0;
		for(int i=0;i<N;i++)
		{
			cin >> A[i];
			sum += A[i];
		}
		if(sum>=L)//可以填满 
		{
			int result = 0;
			sort(A,A+N,cmp);//排序 
			
			for(int i=0;i<N;i++) 
			{
				if(L>A[i])
				{
					result ++;
					L = L - A[i];
				}
				else
				{
					result ++;
					//L = 0;这句话可以不要了
					break; 
				}
				//上面的for循环的循环体可以作如下简化
				/*
				if(L==0)	break;
				result ++;
				L = L - std::min(L,A[i]);
				*/
			}
			cout << result << endl;
		}
		else
			cout << "impossible" << endl;
	}
	
	return 0;
}
上述代码,提交可以通过.

原文地址:https://www.cnblogs.com/tensory/p/6590765.html