#include <stdio.h>
#include<stdlib.h>
#define MAXSIZE 100 //假设物体总数
#define M 20 //背包的载荷能力
//算法核心,贪心算法
void GREEDY(float w[], float x[], int sortResult[], int n)
{
float cu = M;
int i = 0;
int temp = 0;
for (i = 0; i < n; i++)//准备输出结果
{
x[i] = 0;
}
for (i = 0; i < n; i++)
{
temp = sortResult[i];//得到取物体的顺序
if (w[temp] > cu)
{
break;
}
x[temp] = 1;//若合适则取出
cu -= w[temp];//将容量相应的改变
}
if (i <= n)//使背包充满
{
x[temp] = cu / w[temp];
}
}
//得到本算法的所有输入信息
void getData(float p[], float w[], int *n)
{
int i = 0;
printf("please input the total count of object: ");
scanf("%d", n);
printf("Please input array of p :\n");
for (i = 0; i < (*n); i++)
{
scanf("%f", &p[i]);
}
printf("Now please input array of w :\n");
for (i = 0; i < (*n); i++)
{
scanf("%f", &w[i]);
}
}
void output(float x[], int n)
{
int i;
printf("---------------------------------------------\n");
for (i = 0; i < n; i++)
{
printf("x[%d]\t\t", i);
}
printf("\n");
for (i = 0; i < n; i++)
{
printf("%-8.5f\t", x[i]);
}
printf("\n");
printf("----------------------------------------------\n");
}
void SortIndex(float tempArray[], int sortResult[], int n)
{
int i, j, index, max;
max = tempArray[0];
index = 0;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(max < tempArray[j])
{
max = tempArray[j];
index = j;
}
}
sortResult[i] = index;
tempArray[index] = 0;
max = 0;
}
}
int main()
{
float p[MAXSIZE], w[MAXSIZE], x[MAXSIZE];
int i = 0, n = 0;
int sortResult[MAXSIZE];
getData(p, w, &n);
for(i = 0; i < n; i++)
{
x[i] = p[i] / w[i];
}
SortIndex(x, sortResult, n);
GREEDY(w, x, sortResult, n);
output(x, n);
return 0;
}
|