更新时间:2015-10-14 19:37:58浏览次数:1+次
在直接用此算法时,可以有如下的一段代码:
//根据效益tempArray[i]对重量w[i]排序,为进入贪心算法作准备
void sort(float tempArray[], flaot w[], int n)
{
int i = 0, j = 0;
int index = 0;
//用类似冒泡排序算法,根据效益p[i]/w[i]对w[i]排序
for (i = 0; i < n; i++)
{
float swapMemory = 0;
float temp;
temp = tempArray[i];
index = i;
for (j = i + 1; j < n; j++)
{
if (temp < tempArray[j])
{
temp = tempArray[j];
index = j;
}
}
//对w[i]排序
swapMemory = w[index];
w[index] = w[i];
w[i] = swapMemory;
}
return;
}
然而仔细对算法分析后可以发现,“拿来主义”在这里用不上了!
据此,做出一些修改,得到了如下的一段代码:
void sort(float tempArray[], int sortResult[], int n)
{
int i = 0, j = 0;
int index = 0, k = 0;
for (i = 0; i < n; i++)//对映射数组赋初值0
{
sortResult[i] = 0;
}
for (i = 0; i < n; i++)
{
float swapMemory = 0;
float temp;
temp = tempArray[i];
index = i;
for (j = i; j < n; j++)
{
if ((temp < tempArray[j]) && (sortResult[j] == 0))
{
temp = tempArray[j];
index = j;
}
}
if (sortResult[index] == 0)
{
sortResult[index] = ++k;
}
}
for (i = 0; i < n; i++)
{
if (sortResult[i] == 0)
{
sortResult[i] = ++k;
}
}
return;
}
修改后最大的一个改变是没有继续沿用直接对w[i]排序,而是用w[i]的一个映射数组
详细代码:
#include <stdio.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];
}
return;
}
void sort(float tempArray[], int sortResult[], int n)
{
int i = 0, j = 0;
int index = 0, k = 0;
for (i = 0; i < n; i++)//对映射数组赋初值0
{
sortResult[i] = 0;
}
for (i = 0; i < n; i++)
{
float temp = tempArray[i];
index = i;
//找到最大的效益并保存此时的下标
for (j = 0; j < n; j++)
{
if ((temp < tempArray[j]) && (sortResult[j] == 0))
{
temp = tempArray[j];
index = j;
}
}
//对w[i]作标记排序
if (sortResult[index] == 0)
{
sortResult[index] = ++k;
}
}
//修改效益最低的sortResult[i]标记
for (i = 0; i < n; i++)
{
if (sortResult[i] == 0)
{
sortResult[i] = ++k;
}
}
return;
}
//得到本算法的所有输入信息
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]);
}
return;
}
void output(float x[], int n)
{
int i;
printf("\n\nafter arithmetic data: advise method\n");
for (i = 0; i < n; i++)
{
printf("x[%d]\t", i);
}
printf("\n");
for (i = 0; i < n; i++)
{
printf("%2.3f\t", x[i]);
}
return;
}
void 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];
}
sort(x, sortResult, n);
GREEDY(w, x, sortResult, n);
output(x, n);
getch();
}
相关资讯