贪心算法 - 三种贪心选择策略 - 求解0-1背包问题

本文探讨了使用贪心算法解决0-1背包问题的方法,通过三种不同的贪心策略:单价、重量和单位价值,实现了近似最优解的求解过程,并通过Java程序演示了每种策略下选择物品的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

贪心算法能解决背包问题,但是不能解决0-1背包问题.

用算法问解0-1背包问题时,其解不一定是最优解,得到的可能是近似最优解.

根据选择的贪心策略选择的不同,得到的近似最优解也不尽相同.

 

/*
@author jarg
@TODO 贪心算法 - 求解0-1背包问题
贪心策略: 1. 单价 2. 重量 3. 单位价值
*/

import java.util.*;

public class Knapsack
{
	public static int m = 10;						// 背包容量
	public static int n = 4;						// 物品个数
	public static int[] w = {7, 3, 4, 5};			// 物品重量
	public static int[] v = {12, 12, 40, 25};		// 物品单价

	/* 排序结果 */
	public static int[] sort = new int[n];
	public static int[] choice = new int[n];

	public static void main(String[] args)
	{
		greedyByValue();
		greedyByWeight();
		greedyByPrice();
		System.out.println("");
	}

	/* 单价贪心策略 type:0 */
	public static void greedyByValue()
	{
		System.out.println("-单价贪心策略:");
		choice(0);
	}

	/* 重量贪心策略 type:1 */
	public static void greedyByWeight()
	{
		System.out.println("-重量贪心策略:");
		choice(1);
	}

	/* 单位价值贪心策略 type:2 */
	public static void greedyByPrice()
	{
		System.out.println("-单位价值贪心策略:");
		choice(2);
	}

	public static void choice(int type)
	{
		sort(type);
		//display(choice);

		int tempW = 0;
		for(int i=0;i<n;i++)
		{
			tempW = tempW + w[choice[i]];
			if(tempW<m)
			{
				sort[i] = choice[i];
			}
			else
			{
				sort[i] = -1;
			}
		}
		display(sort);
		
	}

	/* 排序 */
	public static void sort(int type)
	{
		int[] temp = getTempData(type);
		
		for(int i=0;i<n;i++)
		{
			choice[i] = i;
		}

		for(int i=0;i<n-1;i++)
		{
			for(int j=i+1;j<n;j++)
			{
				if(temp[j]>temp[i])
				{
					int t = choice[j];
					choice[j] = choice[i];
					choice[i] = t;

					t = temp[j];
					temp[j] = temp[i];
					temp[i] = t;
				}
			}
		}
		
	}

	public static int[] getTempData(int type)
	{
		/* 待排序的数据 */
		int[] temp = new int[n];
		if(type == 0)
		{
			temp = v;
		}
		else if(type == 1)
		{
			temp = w;
		}
		else
		{
			for(int i=0;i<n;i++)
			{
				temp[i] = v[i]/w[i];
			}
		}
		return temp;
	}

	public static void display(int[] value)
	{
		int sumv = 0;
		System.out.print("choice: ");
		for(int i=0;i<n;i++)
		{
			if(sort[i] == -1)
			{
				break;
			}
			sumv = sumv + v[sort[i]] * w[sort[i]];
			System.out.print(sort[i] + "\t");
		}
		System.out.println();
		for(int i=0;i<n;i++)
		{
			if(sort[i] == -1)
			{
				break;
			}
			System.out.println("w[" + sort[i] + "]: " + w[sort[i]] + "\tv[" + sort[i] + "]: " + v[sort[i]]);
		}
		System.out.println("总价值: " + sumv + "\n");
	}
}

 

 

今天浑浑噩噩度过了一下,看贪心算法求解0-1背包问题,不知道思考.

试着写程序,做一半就做不下去.耗了很久.

最终还是决定坚持代码完整性,即使这个程序写得很滥.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值