背包问题(贪婪法)

 

 //................h

typedef struct
{
 float p;
 float w;
 float v;
}OBJECT;

void Print (OBJECT instance[], int n);
void Swamp (OBJECT &instance1, OBJECT &instance2);
float KnapGreedy (float M, OBJECT instance[], float x[], int n);
void SortGreedy (OBJECT instance[], int n);
float SolveGreedy (float M, OBJECT instance[], float x[], int n);
void InitialGreedy (OBJECT instance[], float x[], int n);

//......................cpp

void Print (OBJECT instance[], int n)
{
 for (int i = 0; i < 5; i++)
 {
  cout << instance[i].v << " " << instance[i].w << " " << instance[i].p << endl;
 }
}
void InitialGreedy (OBJECT instance[], float x[], int n)
{
 for (int i = 0; i < n; i++)
 {
  instance[i].p = instance[i].v /instance[i].w;
  x[i] =  0;
 }
 Print(instance, n);

}

void Swamp (OBJECT &instance1, OBJECT &instance2)
{
 OBJECT tmp;
 tmp = instance1;
 instance1 = instance2;
 instance2 = tmp;
}

void SortGreedy (OBJECT instance[], int n)
{
 //冒泡吧
 for (int i = 0; i < n; i++)
  for (int j = n - 1; j > i; j--)
  {
   if (instance[j].p < instance[j - 1].p)
    Swamp (instance[j], instance[j - 1]);
  }
 cout << endl << "maopao here" << endl;
 Print(instance, n);
 cout << endl << "maopao here" << endl;
}

float SolveGreedy (float M, OBJECT instance[], float x[], int n)
{
 float total = 0;
 int i;
 float m = M;
 for (i = 0; i < n; i++)
 {
  if (instance[i].w <= m)
  {
   x[i] = 1;
   m -= instance[i].w;
   total += instance[i].w;
  }else
  {
   x[i] = m / instance[i].w;
   total += x[i] * instance[i].v;
   break;
  }
 }
 return total;
}

float KnapGreedy (float M, OBJECT instance[], float x[], int n)
{
 InitialGreedy(instance, x, n);
 SortGreedy(instance, n);
 return SolveGreedy(M, instance, x, n);
}

//测试

int main (int argc, char *argv[])
{
 float x[5];
 memset (x, 0, sizeof (int) * 5);
 OBJECT instance[5];
 for (int i = 0; i < 5; i++)
 {
  instance[i].v = (rand () + rand () + rand () ) / 100;
  instance[i].w = (rand () + rand () + rand () ) / 50;
  instance[i].p = 0;
 }

 for (int i = 0; i < 5; i++)
 {
  cout << instance[i].w << " " << instance[i].v << " ";
 }
 cout << endl;

 //float KnapGreedy (float M, OBJECT instance[], float x[], int n)
 cout << KnapGreedy(50, instance, x, 5);
 cout << endl;
 for (int i = 0; i < 5; i++)
  cout << x[i] << " " ;
 return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值