前两天看到了一个关于(0/1)背包问题,在网上也看到了很多解决这种问题的很多算法.贪心算法就是其中的一种.
贪心算法有很多的贪心决策,下面的程序中仅有两种(重量优先和利益优先),程序的运行结果可能和背包问题的最优解有很大的误差,这样就必须改变贪心决策,使结果和最优解的误差降低.
贪心算法的运用范围也很广泛,它不仅用于(0/1)背包问题中,还可以运用于一些实际的问题当中.如:仿真机器人足球2D当中的防守决策等
由于本人知识浅薄,程序中有很多不足的地方,还请大家指点!
namespace GreedAlgorithm
{
class Program
{
static void Main(string[] args)
{
int[,] array = { { 1, 2, 3, 4, 5 }, { 3, 2, 7, 4, 1 } };
int weightMax=7;
Algorithm algorithm = new Algorithm(array,weightMax);
Console.WriteLine("按照重量优先的准则:总收益 " + algorithm.weightPriority());
Console.WriteLine("按照利益优先的准则:总收益 " + algorithm.profitPriority());
}
}
class Algorithm
{
private int[,] array;
private int max;
public Algorithm(int[,] _array,int _max)
{
this.array = _array;
max=_max;
}
//使用快速排序法对数组的某一列进行相关的排序
public int partition(int[,] array,int start,int end,int flag)
{
while(start<end)
{
while((start<end)&&(array[flag,start]>array[flag,end]))
{
end--;
}
if(start<end)
{
int temp0=array[0,start];
int temp1=array[1,start];
array[0,start]=array[0,end];
array[1,start]=array[1,end];
array[0,end]=temp0;
array[1,end]=temp1;
start++;
}
while((start<end)&&(array[flag,start]>array[flag,end]))
{
start++;
}
if(start<end)
{
int temp0=array[0,start];
int temp1=array[1,start];
array[0,start]=array[0,end];
array[1,start]=array[1,end];
array[0,end]=temp0;
array[1,end]=temp1;
end--;
}
}
return start;
}
public void quickSort(int[,] array, int start, int end, int flag)
{
if (start < end)
{
int pivot = partition(array, start, end, flag);
quickSort(array, start, pivot - 1, flag);
quickSort(array, pivot + 1, end, flag);
}
}
public void print()
{
for (int i = 0; i <= array.GetUpperBound(0); i++)
{
for (int j = 0; j <= array.GetUpperBound(1); j++)
Console.Write(array[i, j] + " ");
}
Console.WriteLine();
}
//利益优先
public int profitPriority()
{
quickSort(array, 0, 4, 1);
int profitSum = 0;
int weightSum = 0;
for (int i = 0; i <= array.GetUpperBound(1); i++)
{
if ((weightSum + array[0, i]) > max)
{
continue;
}
else
{
weightSum += array[0, i];
profitSum += array[1, i];
}
}
return profitSum;
}
//重量优先
public int weightPriority()
{
quickSort(array, 0, 4, 0);
int profitSum = 0;
int weightSum = 0;
for (int i = 0; i <= array.GetUpperBound(1); i++)
{
if ((weightSum + array[0, i]) > max)
{
continue;
}
else
{
weightSum += array[0, i];
profitSum += array[1, i];
}
}
return profitSum;
}
}
}