杭电oj 1009

题目来源

Problem Description
FatMouse prepared M pounds of cat food, ready to trade with the cats guarding the warehouse containing his favorite food, JavaBean.
The warehouse has N rooms. The i-th room contains J[i] pounds of JavaBeans and requires F[i] pounds of cat food. FatMouse does not have to trade for all the JavaBeans in the room, instead, he may get J[i]* a% pounds of JavaBeans if he pays F[i]* a% pounds of cat food. Here a is a real number. Now he is assigning this homework to you: tell him the maximum amount of JavaBeans he can obtain.


贪心算法,先按照单价从小到大排序,然后按照单价从最便宜的开始买,直到钱用完为止。


package 培训;

import java.util.Scanner;

//贪心
public class 老鼠换猫粮 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);

		while (true) {
			int maoliang = sc.nextInt();
			if (maoliang == -1)
				return;
			int n = sc.nextInt();
			MyData[] array = new MyData[n];
			// 输入具体数据并计算单价信息
			for (int i = 0; i < array.length; i++) {
				array[i] = new MyData();
				array[i].food = sc.nextInt();
				array[i].price = sc.nextInt();
				array[i].priceA = array[i].price / array[i].food;
				array[i].priceB = array[i].food / array[i].price;
			}

			fun(maoliang, array);
		}
	}

	// array=磅数 价格
	static void fun(double maoliang, MyData[] array) {
		double sumFood = 0; // 总共买的粮食
		// MyData[] sortArray = new MyData[array.length];
		// 按照单价排序
		MyData temp = null;
		for (int i = 1; i < array.length; i++) {
			for (int j = 0; j < array.length - i; j++) {
				if (array[j + 1].priceA < array[j].priceA) {
					temp = array[j];
					array[j] = array[j + 1];
					array[j + 1] = temp;
				}
			}
		}
		int buyIndex = 0; // 当前买到第几个
		while (maoliang > 0) {
			// 钱太多 粮食不够
			if (maoliang * array[buyIndex].priceB > array[buyIndex].food) {
				// 这一组全买了
				maoliang = maoliang - array[buyIndex].food
						* array[buyIndex].priceA;
				sumFood += array[buyIndex].food;
				array[buyIndex].food = 0;
				buyIndex++;
			} else {
				sumFood += array[buyIndex].priceB * maoliang;
				array[buyIndex].food -= array[buyIndex].priceB * maoliang;
				maoliang = 0;
			}
		}
		System.out.printf("%.3f\n", sumFood);
	}

	static class MyData {
		double food; // 剩余磅数
		double price; // 价格
		double priceA; // 一磅多少钱
		double priceB; // 一块钱多少磅
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值