栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

背包问题 * 贪心准则:价值贪心

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

背包问题 * 贪心准则:价值贪心

代码

package LQB14;

import java.util.Scanner;


public class T7 {

		public static Scanner scanner = new Scanner(System.in);
		public static int n;// 物品个数
		public static float C;// 背包容量
		public static float[] weight;// 重量数组
		public static float[] value;// 价值数组
		// 拷贝的目的是,在后面对重量数组和价值数组进行了排序,打乱了原来的数组顺序,故先拷贝出来一份。
		public static float[] v;// 拷贝一份价值数组
		public static float[] w;// 拷贝一份重量数组
		public static float[] add;// 放入的比例数组

		public static void main(String[] args) {
			// TODO Auto-generated method stub

			System.out.print("请输入物品的个数:");
			n = scanner.nextInt();
			weight = new float[n];
			value = new float[n];
			v = new float[n];
			w = new float[n];
			System.out.print("请输入背包的容量:");
			C = scanner.nextFloat();
			System.out.println("请输入物品的重量和价值:");
			for (int i = 0; i < n; i++) {
				weight[i] = scanner.nextFloat();
				value[i] = scanner.nextFloat();
				// 进行拷贝
				v[i] = value[i];
				w[i] = weight[i];
			}
			addBag();
			float total = totalValue();
			System.out.println("背包的总价值为:" + total);

		}

		
		public static float totalValue() {
			float total = 0;
			for (int i = 0; i < n; i++) {
				total += add[i] * value[i];
			}
			return total;
		}

		
		public static void addBag() {
			add = new float[n];
			// 给价值数组进行排序,价值大的在前面
			int index[] = Arraysort(value);// 对value进行了排序
			for (int i = 0; i < n; i++) {
				if (w[index[i]] <= C) {
					// 加入背包中
					add[index[i]] = 1;
					C = C - w[index[i]];
				} else {
					// 按比例加入背包中
					add[index[i]] = C / w[index[i]];

				}
			}
			System.out.print("放入重量比例:");
			for (float i : add) {
				System.out.print("t" + i);
			}
			System.out.println();
			System.out.print("单个物品价值:");
			for (float i : value) {
				System.out.print("t" + i);
			}
			System.out.println();
		}

		
		public static int[] Arraysort(float[] arr) {
			float temp;
			int index;
			int k = arr.length;
			int[] Index = new int[k];
			for (int i = 0; i < k; i++) {
				Index[i] = i;
			}

			for (int i = 0; i < arr.length; i++) {
				for (int j = 0; j < arr.length - i - 1; j++) {
					if (arr[j] < arr[j + 1]) {
						temp = arr[j];
						arr[j] = arr[j + 1];
						arr[j + 1] = temp;

						index = Index[j];
						Index[j] = Index[j + 1];
						Index[j + 1] = index;
					}
				}
			}
			return Index;
		}

	}
	



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/309836.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号