数据结构与算法/贪心算法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/li99yangg/article/details/79100790

1、给定 n 种物品和一个背包,物品 i 的重量是 w[i], 其价值是 p[i], 背包的容量为 C。设物品已按单位重量价值递减的次序排序。每种物品不可以装入背包多次,但可以装入部分的物品 i。背包问题是选择装入背包中的物品,在不超过背包容量的前提下使背包的得总价值最大。用贪心法设计与实现一个算法,求解背包问题。

#include <iostream>

#include <stdio.h>

#include <string.h>

using namespace std;

typedef struct

{

    char name[5];

    float value;

    float weight;

    float rate;

}Thing;

typedef struct

{

    Thing thing[3];

    float value;

    float weight;

    float rate;

}Bag;

void sort(Thing thing1,Thing thing2)

{

        Thing temp;

        if(thing1.rate>thing2.rate)

            {

                temp = thing1;

                thing1 = thing2;

                thing2 = temp;

            }

}

int main()

{

    Thing thing[3];

    thing[0].value = 9;thing[1].value = 10;thing[2].value = 12;

    thing[0].weight = 3;thing[1].weight = 5;thing[2].weight = 8;

    thing[0].rate = thing[0].value/thing[0].weight;

    thing[1].rate = thing[1].value/thing[1].weight;

    thing[2].rate = thing[2].value/thing[2].weight;

    strcpy(thing[0].name,"book");

    strcpy(thing[1].name,"note");

    strcpy(thing[2].name,"pen");

    for(int i = 0;i<3;i++)

    {

        for(int j = 0;j<2;j++)

        {

            sort (thing[j],thing[j+1]);

        }

    }

    cout<<"目前总共有以下物品:"<<endl;

    for(int  i = 0 ;i<3;i++)

    {

        cout<<thing[i].name<<" "<<thing[i].value<<" "<<thing[i].weight<<"kg "<<thing[i].rate<<endl;

    }

    Bag bag;

    bag.weight = 14;

    int i = 0;

    bag.rate = 0;

    bag.value = 0;

    while(bag.weight>0)

    {

        if(bag.weight-thing[i].weight >=0)

        {

            bag.weight -= thing[i].weight;

            bag.thing[i].weight = thing[i].weight;

            bag.value +=thing[i].value;

            bag.rate += (bag.weight/14)/100;

            bag.thing[i] = thing[i];

            bag.thing[i].weight = thing[i].weight;

            thing[i].weight = 0;

        }

        else

        {

            bag.thing[i].weight = bag.weight;

            thing[i].weight -= bag.weight;

            bag.value +=thing[i].rate*bag.weight;

            bag.rate = 1;

            strcpy(bag.thing[i].name,thing[i].name);

            bag.weight = 14;

            break;

        }

        if(i == 2)bag.weight = 14 - bag.weight;

        i++;

    }

    cout<<"背包外有以下物品:"<<endl;

    for(int  i = 0 ;i<3;i++)

    {

        cout<<thing[i].name<<" "<<thing[i].weight<<"kg "<<endl;

    }

    cout<<"背包的总重量为:"<<bag.weight<<"kg"<<endl;

    cout<<"背包的承重比例为:"<<bag.rate<<endl;

    cout<<"背包的总价值为:"<<bag.value<<endl;

    cout<<"背包内有以下物品:"<<endl;

    for(int  i = 0 ;i<3;i++)

    {

        if(strcmp(bag.thing[i].name,thing[i].name)==0)

        {

            cout<<bag.thing[i].name<<" "<<bag.thing[i].weight<<"kg "<<endl;

        }

        else break;

    }

}


猜你喜欢

转载自blog.csdn.net/li99yangg/article/details/79100790