`
jishublog
  • 浏览: 868966 次
文章分类
社区版块
存档分类
最新评论

HackerRank Algorithms-Search-Flowers 贪心

 
阅读更多

题目点此

题意:K个小伙伴买N个多花,老板很奇葩,不想买太多花,如果有人已经买过x朵花了,那么买下一朵花就要付x+1倍的价格。给出每朵花的价格,求最少花多少钱都把花买下。

分析:每个小伙伴买花时肯定是先买原价贵的,不然就吃亏了是不是。所以贪心策略就是把价格排序下,先让每个小伙伴把一血献给最贵的那几朵花,每次都买剩下的花最贵的那几朵,这样就是最优的了。

一遍遍历即可,复杂度为O(n)。

代码:

/*
 *   Author:        illuz <iilluzen[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 long LL;
typedef unsigned long 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%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;
}


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics