hdu 2124 Repair the Wall

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

题目大意:下大雨会毁坏墙,毁坏的面积为1*L (inch),现在有砖块宽为1 inch,长即为输入的那些数字。(这里已缩小题目难度,因为损坏的墙宽是1 inch,而对应的砖宽也是1 inch,所以这里修补墙时只需要考虑毁坏的长度不需要再考虑宽度了)由于数略大,必须用64位long long才能过,本题就是一个裸贪心,先用sort由大到小排个序,先选大的去补,需要的块数就少。

代码如下:

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

int cmp1(int a,int b)
{

    return a>b;

}

int main()
{
    long long int L,  sum, a[1000], count1;
    int n;
    while(cin>>L>>n)
    {
        count1=0;
        sum=0;

       for(int i=0;i<n;i++)
          scanf("%lld",&a[i]);//这里为长整型
       sort(a,a+n,cmp1);
         while(sum<L && count1<=n)  //如果小于目标就再加且如果还有剩余的砖块

        {

            sum += a[count1];
            count1++;

        }

        if(count1<=n)//没有用完

            printf("%d\n",count1);

        else if(sum<L || count1 >= n)  //所有砖块用完了

           printf("impossible\n");

    }
    return 0;
 }

猜你喜欢

转载自blog.csdn.net/fanxingxue/article/details/81630973