HackerRank - greedy-florist 【贪心】

mac2022-06-30  26

HackerRank - greedy-florist 【贪心】

题意 有N个人 要去买K朵花。老板为了最大化新顾客的数量。就压榨回头客。每一朵花都有一个基本价格。一个顾客买下这朵花的价格是他来这里买的次数 * 基本价格 打个比方 如果一个顾客第一次来买 它来买的次数就是1,然后求这N个人买下这K朵花最少需要花多少钱。K朵花必须全部买下来,而且每种价格的花只有一种。

思路 如果 N >= K 那么 就直接对K多花的基本价格求和就可以了。 如果 N < K, 那么我们要充分利用每个客户的购买次数。就比如有 6 朵花,3 个人。那么 我们就要每个人买两次 就可以了。 如果 K 对 N 不能整除。 比如 5朵花, 3个人。 那么我们就用 5 / 3 = 1 (整数除法) 就有三个人 买一次,两个人买两次。然后买的次数少的 用来买基本价格多的,买的次数多的 用来买基本价格小的 就是典型的贪心做法。

AC 代码

#include<iostream> #include<cstdio> #include<cmath> #include<cstring> #include<algorithm> #include<string> #include<sstream> #include<set> #include<map> #include<vector> #include<queue> #include<stack> #include<numeric> using namespace std; const int MAX = 0x3f3f3f3f; const int MIN = 0xc0c0c0c0; const int maxn = 1e2 + 5; int pri[maxn]; int main() { int n, k; scanf("%d%d", &n, &k); if (n <= k) { int num; int tot = 0; while (n--) { scanf("%d", &num); tot += num; } cout << tot << endl; } else { int tot = 0; int i, j, l; for (i = 0; i < n; i++) scanf("%d", &pri[i]); sort(pri, pri + n); int a = n / k; int b = n % k; i = 0; int flag = (n - b) / a; while (b--) tot += pri[i++] * (a + 1); for (j = a; j >= 1; j--) { for (l = 0; l < flag; l++) tot += pri[i++] * j; } cout << tot << endl; } }

转载于:https://www.cnblogs.com/Dup4/p/9433407.html

最新回复(0)