码迷,mamicode.com
首页 > 其他好文 > 详细

UVA 1149 Bin Packing

时间:2014-11-04 16:56:46      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   for   sp   

贪心

对所有物品排序,然后从大头拿一个,检测如果加上此时最小的是否满足<=M,是的话就拿,不是的话就不拿

注意此题的输出要求!!!

多组样例的时候,每两组样例中要有一个空行!

而一组样例的时候,不要输出多余的空行。(因为这个WA卡住半个小时T T,最后还是去网上搜别人代码发现的,虽然以前有的题或是OJ会忽略最后一行空行,但是还是改掉这个坏习惯好)

AC代码

bubuko.com,布布扣
#include <iostream>
#include <cstdio> 
#include <algorithm>
#include <cstring>
#define maxn 100000+10
using namespace std;
int a[maxn];
int cmp(int a,int b){
    return a>b;
}
int work(int n,int m){
    int ans=0;
    int i=0,j=n-1;
    while (i<=j){
        if (a[i]+a[j]<=m&&i!=j) j--;
        i++;ans++;
    }
    return ans;
}
int main()
{
    int t=0;
    int testcase;
    scanf("%d",&testcase);
    while (testcase--){
        t++;
        int n,m;
        scanf("%d%d",&n,&m);
        memset(a,0,sizeof(a));
        for (int i=0;i<n;i++) scanf("%d",&a[i]);
        sort(a,a+n,cmp);
        if(t!=1) printf("\n");
        printf("%d\n",work(n,m));
    }
}
View Code

 PS.自己一开始的贪想的有点复杂了,找最大的,然后再找当前能塞下去的最大的。这个思想的正确性我还不确定,但是仔细想想,根本不用这样贪。

UVA 1149 Bin Packing

标签:style   blog   http   io   color   ar   os   for   sp   

原文地址:http://www.cnblogs.com/bingolibing/p/4073862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!