//................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;
}