博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
杭电oj 1009
阅读量:2342 次
发布时间:2019-05-10

本文共 2172 字,大约阅读时间需要 7 分钟。

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; // 一块钱多少磅	}}

转载地址:http://yryvb.baihongyu.com/

你可能感兴趣的文章
Git学习笔记1 神奇的git stash
查看>>
Unable to locate package错误解决办法
查看>>
关于service中添加Transaction注解后,service无法注入bean
查看>>
linux shell 自定义函数(定义、返回值、变量作用域)介绍
查看>>
写自己的ASP.NET MVC框架(上)
查看>>
C++和C在linux下编程和与在WINDOWS下有什么区别
查看>>
CSS 的优先级机制[总结]
查看>>
linux shell 数组建立及使用技巧
查看>>
IEnumerator 协程 全称协同程序
查看>>
java实现冒泡排序
查看>>
spring boot 初试,springboot入门,springboot helloworld例子
查看>>
Spring中配置和读取多个Properties文件--转
查看>>
使用JNI进行Java与C/C++语言混合编程(1)--在Java中调用C/C++本地库
查看>>
Mac 终端命令连接mysql
查看>>
Lua中的数学库
查看>>
多态小结
查看>>
Java连MySQL的驱动mysql-connector-java-5.1.21-bin.jar的安装方法
查看>>
java基础小结
查看>>
线程概念及死锁的理解
查看>>
数据结构之红黑树
查看>>