这个题是在二分的题单上的,可是依据二分法写出来的会在oj上超时。依据题目以下给出的提示能够发现能通过贪心法每次都找最能满足的情况去填充每个包,这样就能保证使用的包的数量是最少的
二分法解法:
#include#include #include #include #define MAX 100000using namespace std;int n,length;int l[MAX];bool cmp(int a,int b){ return a < n;i++){ r = length - l[i]; max = i; for(int j = n-1;j > i;j--){ if((l[j] < r) &&!tag[j]){//尽量找到最能填满剩余空间的物 max = j; break; } } if(!tag[max]){ q++; tag[max] = 1; } } if(q < mid) return false; else return true;}int main(){ int high,low,mid,res; while(cin>>n){ cin>>length; for(int i = 0;i < n;i++){ cin>>l[i]; } sort(l,l+n,cmp); high = n; low = 0; res = 0; while(low <= high){ mid = (low+high)/2; if(judge(mid)){ res = mid; low = mid+1; } else high = mid-1; } cout< <
贪心法解法:
#include#include #include #include #include using namespace std;int li[100003];int ca[100003];bool cmp(int a,int b){ return a>b;}int main(){#ifndef ONLINE_JUDGE freopen("in.txt","r",stdin);#endif int n; int l; while(scanf("%d",&n)!=EOF) { scanf("%d",&l); for(int i=0;i