HackerRank - greedy-florist 【贪心】
2018-03-01 21:40
260 查看
HackerRank - greedy-florist 【贪心】
![](https://img-blog.csdn.net/20180301213221975?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRHVwNHBseg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
![](https://img-blog.csdn.net/20180301213236424?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvRHVwNHBseg==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70)
题意
有N个人 要去买K朵花。老板为了最大化新顾客的数量。就压榨回头客。每一朵花都有一个基本价格。一个顾客买下这朵花的价格是他来这里买的次数 * 基本价格 打个比方 如果一个顾客第一次来买 它来买的次数就是1,然后求这N个人买下这K朵花最少需要花多少钱。K朵花必须全部买下来,而且每种价格的花只有一种。
思路
如果 N >= K 那么 就直接对K多花的基本价格求和就可以了。 如果 N < K, 那么我们要充分利用每个客户的购买次数。就比如有 6 朵花,3 个人。那么 我们就要每个人买两次 就可以了。 如果 K 对 N 不能整除。 比如 5朵花, 3个人。 那么我们就用 5 / 3 = 1 (整数除法) 就有三个人 买一次,两个人买两次。然后买的次数少的 用来买基本价格多的,买的次数多的 用来买基本价格小的 就是典型的贪心做法。
AC 代码
题意
有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; } }
相关文章推荐
- HackerRank Algorithms-Search-Flowers 贪心
- HackerRank Medium(30) Maximal AND Subsequences 贪心+计数
- HackerRank - candies 【贪心】
- [hackerrank]Weekly Challenges - Week 11
- HackerRank - Python部分
- HDU 4221 Greedy?(贪心)
- HackerRank "Array and simple queries" !
- Hackerrank--Ashton and String (后缀数组)
- HackerRank Truck Tour
- 【Hacker Rank】04.Arithmetic Operators
- [hackerrank Value of all Permutations]
- codeforces #422 C. Hacker, pack your bags!(贪心dp)
- HackerRank "Bonetrousle"
- 贪心算法也挺好-Greedy is Good
- Hackerrank - The Grid Search
- HackerRank "Dijkstra: Shortest Reach 2"
- hackerrank初级篇之simplesum
- Greedy? HDU - 4221 (贪心)
- HackerRank - string-reduction【反推】【规律】
- C++ HackerRank|Waiter