8-1 binpacking uva1149(贪心)

  题意:给定N个物品的重量Li  背包的容量M 同时要求每个背包最多装两个物品 求至少要多少个背包才能装下所有物品 

简单贪心  注意输出:

#include<bits/stdc++.h>
using namespace std;
#define N 200000+5
int n,w;
int a[N];
int main()
{
    int cas;cin>>cas;
    while(cas--)
    {
        cin>>n>>w;
        for(int i=0;i<n;i++)
            scanf("%d",&a[i]);
        sort(a,a+n);
        int cnt=0;
        int L=0,R=n-1;
        while(L<=R)
        {
            int t=a[L];
            cnt++;
            while(t+a[R]>w&&L<R){R--;cnt++;}
            R--;
            L++;
        }
          printf("%d
",cnt);
          if(cas)cout<<endl;
    }
    return 0;
}
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=1e5+50;
int a[maxn];
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        int n,l;
        scanf("%d%d",&n,&l);
        for(int i=0;i<n;i++)scanf("%d",a+i);
        sort(a,a+n);
        int count =0;
        int min=0,max=n-1;
        while(min<=max){
             if(a[min]+a[max]<=l){
                min++;
                max--;
                count++;
            }
            else {
                count++;
                max--;
        }
    }
        printf("%d
",count);
        if(T>0)printf("
");
    } 
    return 0;
} 
原文地址:https://www.cnblogs.com/bxd123/p/10443255.html