#include <iostream>
using namespace std;
#define NUM 50
void Knapsack(int n,float M,float v[],float w[],float x[])
{
int i;
for(i = 1; i <= n; i++) x[i] = 0;
float c = M;
for(i = 1;i <= n; i++)
{
if(w[i]>c) break;
x[i] = 1;
c -= w[i];
}
if(i <= n) x[i] = c / w[i];
}
int main()
{
float M = 50;
float w[] = {0,10,20,30};
float v[] = {0,60,100,120};
float x[NUM];
int n = (sizeof(w) / sizeof(w[0])) - 1;
Knapsack(n, M, v, w, x);
for(int i = 1; i <= n; i++)
cout << "物品 " << i << " 装入的比例: " << x[i] << endl;
return 0;
}
背包问题(贪心算法)
最新推荐文章于 2022-11-26 09:13:05 发布