Description
有一批集裝箱要裝上一艘載重量為c的輪船。其中集裝箱i的重量為Wi。最優裝載問題要求確定在裝載體積不受限制的情況下,將盡可能多的集裝箱裝上輪船。 編程任務: 對于給定的n個集裝箱和輪船的載重量C,編程計算裝入最多時的集裝箱個數。
Input
輸入由多組測試數據組成。 每組測試數據輸入的第1行中有2個正整數n和C。正整數n是集裝箱個數;正整數C是輪船的載重量。接下來的一行中有n個整數,分別表示n個集裝箱的重量,它們之間用空格分隔。
Output
對應每組輸入,輸出的每行是計算出的裝入最多時的集裝箱個數。
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;}