贪心算法
来源:互联网 发布:淘宝达人入口在哪 编辑:程序博客网 时间:2024/04/29 12:21
Description
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.
Input
Output
Sample Input
5 37 24 35 220 325 1824 1515 10-1 -1
Sample Output
13.33331.500
sort函数要和using namespace std;和头文件联合使用。
贪心的思路。对当前的数据进行排序,然后依次对最大的或者最小的进行操作。
第二周培训A题,很简单。但是runtime error。
runtime error代码
#include <stdio.h>
#include <string.h>
int main()
{
static double M,N,J[101],F[100];
while(scanf("%lf %lf",&M,&N) != EOF)
{
if(M == -1&&N == -1) break;
else
{
double ans = 0;
double JS[101];
for(int i = 0;i < N;i++)
{
scanf("%lf %lf",&J[i],&F[i]);
JS[i] = J[i]/F[i];
}
//for(int i = 0;i<N;i++)printf("%lf\n",JS[i]);
double max;
int Imax;
max = JS[0];Imax=0;
for(int i = 0;i<N;i++)
{
if(JS[i]>max)
{
max = JS[i];
Imax = i;
}
}
while(M>F[Imax])
{
ans += J[Imax];
M =M - F[Imax];
JS[Imax] = 0;
max = 0;
for(int i = 0;i<N;i++)
{
if(JS[i]>max)
{
max = JS[i];
Imax = i;
}
}
//printf("%lf %d\n",max,Imax);
//printf("%.3lf\n",ans);
}
ans += M*JS[Imax];
printf("%.3lf\n",ans);
}
}
return 0;
}
AC代码(拷的)
- #include <iostream>
- #include <cstdio>
- #include <algorithm>
- using namespace std;
- const int maxn = 10005;
- struct W {
- double get;//收入
- double pay;//付出的猫食
- double ave;//收入/付出比
- } w[maxn];
- bool cmp(W a, W b) {
- if (a.ave > b.ave) {
- return true;
- }
- return false;
- }
- int main() {
- int n;
- double m;
- while (scanf("%lf%d", &m, &n), n != -1 && m != -1) {
- int i;
- for (i = 0; i < n; ++i) {
- scanf("%lf %lf", &w[i].get, &w[i].pay);
- w[i].ave = w[i].get / w[i].pay;
- }
- sort(w, w + n, cmp);//贪心,对w按照get/pay进行降序排序
- double sum = 0;
- i = 0;
- // while(m >= 0){//不知道为什么这种写法就是不行.
- // if (m >= w[i].pay) {
- // sum = sum + w[i].get;
- // m = m - w[i].pay;
- // } else {
- // sum = sum + w[i].ave * m;
- // break;
- // }
- // i++;
- // }
- for (i = 0; i <= n - 1; i++) {
- if (m >= w[i].pay) {//如果当前剩余的猫食还足够的话
- sum = sum + w[i].get;//那就把那个房间的粮食全部买下
- m = m - w[i].pay;//并且手上见去相应的猫食
- } else {//如果现在手上的猫食已经不够
- sum = sum + w[i].ave * m;//那么就按比例拿去一定的猫食
- break;
- }
- }
- printf("%.3lf\n", sum);
- }
- return 0;
- }
- 【贪心】贪心算法总结
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 贪心算法
- 活动安排问题-贪心算法
- javaweb_会话
- Spring data jpa 之 Query注解
- 图形数据结构--保留连接性质的网格存储结构
- Android 高效调试神器 JRebel
- 贪心算法
- ajax+php文件上传代码 - php上传下载
- 智能城市方案:OpenStack合力K8s打造IoT平台
- POJ 3169 差分约束系统 + spfa
- Ping命令详解
- leetcode 384- Shuffle an Array --STL shuffle算法的实现
- php验证码实现代码(3种)验证类
- Mysql 大数据量高并发的数据库优化
- 数值分析: 病态问题 & 算法稳定