码迷,mamicode.com
首页 > 其他好文 > 详细

PAT 1020

时间:2020-07-24 22:06:42      阅读:73      评论:0      收藏:0      [点我收藏+]

标签:有一个   print   ret   printf   max   return   can   name   space   

技术图片

第一种做法(21分)

#include <iostream>
#include<stdio.h>
#include<iomanip>

int main()
{

int input,need; //input代表月饼种类 ,need代表市场需要吨数
scanf("%d %d",&input,&need);
int *store = new int[input];  //存储每种的月饼吨数
int *price = new int[input];  //存储每种月饼的总售价
double *money = new double[input];  //存储每种月饼每吨的单售价

for(int i=0;i<input;++i)
{
    scanf("%d",&store[i]);
}

for(int j=0;j<input;++j)
{
    scanf("%d",&price[j]);
}

for(int w=0;w<input;++w)
{
    money[w] = double(price[w])/double(store[w]);
}


int flag=0;  //储存最大单价的位置
double answer=0.0;

while(need!=0)
{
    double max=money[0];  //注意是两个double类型的数在进行比较
    for(int x=1;x<input;++x)
    {
        if(money[x] > max)
        {
            max = money[x];
            flag= x;
        }
        if(money[x]==0) continue;
    }

    while(store[flag]!=0 && need!=0)
    {
       need--;
       store[flag]--;
       answer += max*1;
    }
    money[flag]=0;  //将已找到的最大值归零,避免下次重复找到
}

printf("%.2f\n",answer);
return 0;

}
PS:由于算法复杂度太大,运算超时,所以有两个监测点超时。

第二种做法(23分) 避免了找最大值等操作,减少了算法复杂度

double money[10000000]; //存储每种月饼每吨的单售价
int main()
{

int input,need; //input代表月饼种类 ,need代表市场需要吨数
scanf("%d %d",&input,&need);
int *store = new int[input];  //存储每种的月饼吨数
int *price = new int[input];  //存储每种月饼的总售价

for(int i=0;i<input;++i)
{
    scanf("%d",&store[i]);
}

for(int j=0;j<input;++j)
{
    scanf("%d",&price[j]);
}

int temp=0;
for(int w=0;w<input;++w)
{
    for(int x=0;x<store[w];++x)
    {
        money[temp++] = (double)price[w]/store[w];
    }
}

sort(money,money+temp,greater<double>()); //降序排序

double answer=0;

for(int y=0; y<need;y++)
{
    answer += money[y];
}

printf("%0.2lf",answer);

return 0;

}
PS:但还是有一个监测点过不了。

第三种做法(25分) 是网上大佬利用结构体做的,但是任然想不通为什么我的第二种做法是会出错。

对于此类问题还是用结构体比较方便处理。

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
double list[10000000];
struct mooncake {
double num; //库存
double tol; //总价
}cake[1000];

int main() {
int n;
double D, sum = 0;
int count = 0;
cin >> n >> D;//种类 需求
for (int i = 0; i < n; i++)
cin >> cake[i].num;
for (int i = 0; i < n; i++)
cin >> cake[i].tol;
for (int i = 0; i < n; i++)
for (int j = 0; j < cake[i].num; j++)
list[count++] = (double)cake[i].tol / cake[i].num; //存放num个单价(以万吨为单位)
sort(list, list + count, greater<double>()); //降序排序 比较算子,大的往后排,小的往前排,小的先出队
for (int i = 0; i < D; i++) //累加前D万吨的和就是最大收益
sum += list[i];
printf("%0.2lf", sum);
return 0;
}

PAT 1020

标签:有一个   print   ret   printf   max   return   can   name   space   

原文地址:https://www.cnblogs.com/kayden-su/p/13374019.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!