HackerRank Algorithms-Search-Flowers greedy

Source: Internet
Author: User

Q: K friends buy N more flowers. The boss is wonderful and doesn't want to buy too many flowers. If someone has already bought x flowers, the price of x + 1 is required to buy a flower. The price of each flower is given, and the minimum amount of money is required to buy the flower. Analysis: each small partner must first buy the original price when buying flowers, or else it will suffer. Therefore, the greedy strategy is to sort the prices first, so that each small partner can give a blood to the most expensive flowers, and each time they buy the most expensive flowers, this is the best. The complexity is O (n ). Code:

/** Author: Author z <iw.zen [at] gmail.com> * Blog: http://blog.csdn.net/hcbbt * File: Flowers. cpp * Lauguage: C/C ++ * Create Date: 2013-09-06 15:46:01 * Descripton: flowers */# include <cstdio> # include <algorithm> using namespace std; # define rep (I, n) for (int I = 0; I <(n); I ++) typedef long LL; typedef unsigned long ULL; const int MAXN = 110; int a [MAXN]; int n, k; LL sum = 0; bool cmp (int a, int B) {return a> B ;} int main () {scanf ("% d", & n, & k); rep (I, n) scanf ("% d ", & a [I]); sort (a, a + n, cmp); rep (I, n) sum + = a [I] * (I/k + 1 ); printf ("% lld \ n", sum); return 0 ;}

 


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.