Description
有一批集裝箱要裝上一艘載重量為c的輪船。其中集裝箱i的重量為Wi。最優(yōu)裝載問題要求確定在裝載體積不受限制的情況下,將盡可能多的集裝箱裝上輪船。 編程任務(wù): 對(duì)于給定的n個(gè)集裝箱和輪船的載重量C,編程計(jì)算裝入最多時(shí)的集裝箱個(gè)數(shù)。
Input
輸入由多組測(cè)試數(shù)據(jù)組成。 每組測(cè)試數(shù)據(jù)輸入的第1行中有2個(gè)正整數(shù)n和C。正整數(shù)n是集裝箱個(gè)數(shù);正整數(shù)C是輪船的載重量。接下來的一行中有n個(gè)整數(shù),分別表示n個(gè)集裝箱的重量,它們之間用空格分隔。
Output
對(duì)應(yīng)每組輸入,輸出的每行是計(jì)算出的裝入最多時(shí)的集裝箱個(gè)數(shù)。
Sample Input
4 5 3 5 2 1
Sample Output
2 #include<iostream>#include<stdio.h>#include<queue>using namespace std;struct Node { int weight; friend bool operator <(Node a,Node b) { return a.weight > b.weight; }};int main(){ int n,c,num,sum; Node p; while(cin>>n>>c) { priority_queue<Node>Q; while(n--) { scanf("%d",&p.weight); Q.push(p); } num = sum = 0; while(!Q.empty()) { p = Q.top(); Q.pop(); sum += p.weight; num ++; if(sum > c) { num --; break; } } cout<<num<<endl; } return 0;}
2
#include<iostream>#include<stdio.h>#include<queue>using namespace std;struct Node { int weight; friend bool operator <(Node a,Node b) { return a.weight > b.weight; }};int main(){ int n,c,num,sum; Node p; while(cin>>n>>c) { priority_queue<Node>Q; while(n--) { scanf("%d",&p.weight); Q.push(p); } num = sum = 0; while(!Q.empty()) { p = Q.top(); Q.pop(); sum += p.weight; num ++; if(sum > c) { num --; break; } } cout<<num<<endl; } return 0;}