设有n个程序{1,2,3,…,n}要存放在长度为L的磁带上。程序i存放在磁带上的长度是li,1≤i≤n。要求确定这n个程序在磁带上的一个存储方案,使得能够在磁带上存储尽可能多的程序。输入数据中,第一行是2个正整数,分别表示程序文件个数和磁带长度L。接下来的1行中,有n个正整数,表示程序存放在磁带上的长度。输出为最多可以存储的程序个数。
输入数据示例
6 50
2 3 13 8 80 20
输出数据
5
public class SaveProgram {
//文件长度
public int [] sizes = new int[]{2,3,13,8,80,20};
//文件个数
public int count = 6;
//磁盘长度
public int l = 50;
//实现排序
public void quickSort(int [] a,int left,int right){
if(left < right){
int low = left;
int high = right;
int privot = a[left];
while(low < high){
while(low < high && a[high] >= privot){
high--;
}
a[low] = a[high];
while(low < high && a[low] <= privot ){
low++;
}
a[high] = a[low];
}
a[low] = privot;
quickSort(a,left,low-1);
quickSort(a,low+1,right);
}
}
//输出
public void print(){
quickSort(sizes, 0, count-1);
int sum = 0;
int c = 0;
for(int i = 0;i < count;i++){
sum = sum + sizes[i];
if(sum <= l){
c++;
}else{
break;
}
}
System.out.println("存储程序个数:"+c);
}
public static void main(String[] args) {
new SaveProgram().print();
}
}