算法学习:贪心

一直向前!贪心法

贪心法:遵循某种规则,不断贪心地选取当前最优策略的算法设计方法。(简单的思维题?)

为了更容易理解贪心,我下面将用几道简单的例题讲解

LuoGu AT277 たこ焼き買えるかな?

你要买 N 个东西,1个15元,10个100元,求最少花费。 你可以购买 N 个以上的物品。
很简单的题目,唯一注意的就是 当7个及7个以上时就得买100个了(这里说了N个以上 所以不用考虑你所购买的数量>你现在所需要的数量)

扔代码~

//#define fre yes

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;

template<typename T>inline void read(T&x)
{
    x = 0;char c;int lenp = 1;
    do { c = getchar();if(c == '-') lenp = -1; } while(!isdigit(c));
    do { x = x * 10 + c - '0';c = getchar(); } while(isdigit(c));
    x *= lenp;
}

int main()
{
    int n;
    read(n);
    
    int p = n/10 * 10;
    n -= p;

    int w = 0;
    if(n >= 7) w = 100;
    else w = n*15;

    printf("%d\n",p*100+w);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Steinway/p/9205686.html