NOIP普及组:买铅笔

参加考试的时候,第一题我足足花了四十多分钟(因为那奇葩的键盘,幸好我向老师报告更换了键盘),还是只得了五十分。。。

题目描述:

P老师需要去商店买n支铅笔作为小朋友们参加NOIP的礼物。她发现商店一共有 3种包装的铅笔,不同包装内的铅笔数量有可能不同,价格也有可能不同。为了公平起 见,P老师决定只买同一种包装的铅笔。

商店不允许将铅笔的包装拆开,因此P老师可能需要购买超过n支铅笔才够给小朋 友们发礼物。

现在P老师想知道,在商店每种包装的数量都足够的情况下,要买够至少n支铅笔最少需要花费多少钱。

然后贴一下50分代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int n, p[4], v[4], ans[4];
int main() {
    freopen("pencil.in", "r", stdin);
    freopen("pencil.out", "w", stdout);
    scanf("%d", &n);
    for (int i = 1; i <= 3; i++) {
        scanf("%d%d", &p[i], &v[i]);
    }
    for (int i = 1; i <= 3; i++) {
        ans[i] = int(double(n) / p[i] + 1) * v[i];
    }
    ans[0] = min(ans[1], ans[2]);
    ans[0] = min(ans[0], ans[3]);
    printf("%d
", ans[0]);
    return 0;
}

这题是简单的数学计算,然后比较最小值。

出错的地方是 ans[i]=int(double(n)/p[i]+1)*v[i]; 这一句上。

我的想法是让 n/p[i] 得到的值是小数位补足进1的。而真正的int和int相除的得数是默认舍去小数为的,与自动补足进1相反。所以我捣鼓了半天,样例数据过了,还是没有拿到满分。

而真正的进1补满方法是

if (n % p[i] == 0) ans[i] = (n / p[i]) * v[i];
else               ans[i] = (n / p[i] + 1) * v[i];

贴上满分代码:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
using namespace std;
int n, p[4], v[4], ans[4];
int main() {
    freopen("pencil.in", "r", stdin);
    freopen("pencil.out", "w", stdout);
    scanf("%d", &n);
    for (int i = 1; i <= 3; i++) {
        scanf("%d%d", &p[i], &v[i]);
    }
    for (int i = 1; i <= 3; i++) {
        if (n % p[i] == 0) ans[i] = (n / p[i]) * v[i];
        else               ans[i] = (n / p[i] + 1) * v[i];
    }
    ans[0] = min(ans[1], ans[2]);
    ans[0] = min(ans[0], ans[3]);
    printf("%d
", ans[0]);
    return 0;
}

 


Post author 作者: Grey
Copyright Notice 版权说明: Except where otherwise noted, all content of this blog is licensed under a CC BY-NC-SA 4.0 International license. 除非另有说明,本博客上的所有文章均受 知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议 保护。
原文地址:https://www.cnblogs.com/greyqz/p/6371380.html