Program storage
Time Limit: 1000 MS Memory Limit: 65536 Kb Total Submission: 701 Accepted: 298
Description
设有n 个程序{1,2,…, n }要存放在长度为L的磁带上。程序i存放在磁带上的长度是 Li,程序存储问题要求确定这n 个程序在磁带上的一个存储方案,使得能够在磁带上存储尽可能多的程序。对于给定的n个程序存放在磁带上的长度,编程计算磁带上最多可以存储的程序数。
Input
多组测试数据。每组测试数据第一行是2 个正整数,分别表示文件个数n(n≤1000)和磁带的长度L。接下来的1 行中,有n个正整数,表示程序存放在磁带上的长度。
Output
输出每组测试数据的最多可以存储的程序数,每组测试数据输出单独一行。
Sample Input
6 502 3 13 8 80 20
Sample Output
5
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <string>
#include <algorithm>
using namespace std;
const int MAXN = 1000 + 10;
int tape[MAXN];
bool cmp(const int& a, const int& b)
{
if(a < b) return true;
else return false;
}
int main()
{
int n, l;
while(cin >> n >> l)
{
memset(tape, 0, sizeof tape);
for(int i = 0; i < n; i++)
{
cin >> tape[i];
}
sort(tape, tape + n, cmp);
int cnt = 0;
int sum = 0;
for(int i = 0; i < n; i++)
{
sum += tape[i];
if(sum <= l)
{
cnt++;
}
else
{
break;
}
}
cout << cnt << endl;
}
return 0;
}
(贪心算法)
本文介绍了如何通过贪心算法解决程序存储问题,即在有限长度的磁带上存储尽可能多的程序。通过实例分析,详细阐述了算法实现步骤和关键逻辑,旨在提供一种有效解决方案。
5226

被折叠的 条评论
为什么被折叠?



