《算法笔记》例题解析 第4章算法初步--4贪心(9题)2021-03-07

喝饮料

题目描述

Time Limit: 1000 ms
Memory Limit: 256 mb
商店里有n中饮料,第i种饮料有mi毫升,价格为wi。
小明现在手里有x元,他想吃尽量多的饮料,于是向你寻求帮助,怎么样买才能吃的最多。
请注意,每一种饮料都可以只买一部分。

输入描述:

有多组测试数据。
第一行输入两个非负整数x和n。
接下来n行,每行输入两个整数,分别为mi和wi。
所有数据都不大于1000。
x和n都为-1时程序结束。

输出描述:

请输出小明最多能喝到多少毫升的饮料,结果保留三位小数。

代码
#include <stdio.h>
#include <algorithm>
using namespace std;


struct node {
	double w, m;//m毫升,w元
}p[1005];
bool cmp(node a,node b) {
	return (a.w / a.m) < (b.w / b.m);
}

int main() {
	int n;
	double x;//n种饮料,x元钱
	while (scanf("%lf %d",&x,&n)!=EOF){
		if (x == -1 && n == -1)	break;
		for (int i = 0; i < n; i++) {
			scanf("%lf %lf",&p[i].m,&p[i].w); 
		}
		sort(p,p+n,cmp);
		double ans = 0;//用于记录可以喝的水的毫升
		for (int i = 0; i < n;i++) {
			if (x >= p[i].w){
				ans += p[i].m;
				x -= p[i].w;
			}
			else {
				ans += (x / p[i].w*p[i].m);
				break;
			}
		}
		printf("%.3f\n",ans);
	}
	return 0;
}

组队刷题

题目描述

Time Limit: 1000 ms
Memory Limit: 256 mb
某天,吴大佬准备和菜鸡Tirpitz一起组队刷题,聪明的吴大佬把题目分成了n个板块,每个板块有w[i]个题目,刷完这个板块需要消耗吴大佬m[i]的精力。吴大佬没有必要在一个板块死磕,/毕竟有咸鱼队友Tirpitz/。相反,如果他消耗m[i]%的精力时,他会解决这个专题w[i]%的题目,现在吴大佬想给聪明的你一个任务,让你计算吴大佬一共能做多少道题目?(没有a完就算成小数累加哦w/这个也算是吴大佬的贡献嘛/)

输入输出格式
输入描述:
输入由多个测试用例组成,每个测试用例是有两个非负整数m(总的精力),n的行作为第一行,然后后面有n行跟随,每行包括两个非负整数w[i],m[i],最后一个测试用例后面有一组 -1 -1(所有的整数都不大于1000,毕竟人类是有极限的嘛hhh)
输出描述:
对于每一个测试用例,在一行中输出吴大佬可以做出的题目数目,精确到小数点后3位

代码
在这里插入代码片

To Fill or Not to Fill

题目描述

Time Limit: 1000 ms
Memory Limit: 256 mb
With highways available, driving a car from Hangzhou to any other city is easy. But since the tank capacity of a car is limited, we have to find gas stations on the way from time to time. Different gas station may give different price. You are asked to carefully design the cheapest route to go.

输入描述:

For each case, the first line contains 4 positive numbers: Cmax (<= 100), the maximum capacity of the tank; D (<=30000), the distance between Hangzhou and the destination city; Davg (<=20), the average distance per unit gas that the car can run; and N (<= 500), the total number of gas stations. Then N lines follow, each contains a pair of non-negative numbers: Pi, the unit gas price, and Di (<=D), the distance between this station and Hangzhou, for i=1,…N. All the numbers in a line are separated by a space.

输出描述:

For each test case, print the cheapest price in a line, accurate up to 2 decimal places. It is assumed that the tank is empty at the beginning. If it is impossible to reach the destination, print “The maximum travel distance = X” where X is the maximum possible distance the car can run, accurate up to 2 decimal places.

代码
在这里插入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值