The Third Cup is Free
题目描述:
Panda and his friends were hiking in the forest. They came across a coffee bar inside a giant tree trunk.
Panda decided to treat everyone a cup of coffee and have some rest. Mr. Buck, the bartender greeted Panda and his animal friends with his antler. He proudly told them that his coffee is the best in the forest and this bar is a Michelin-starred bar, thats why the bar is called Starred Bucks.
There was a campaign running at the coffee bar: for every 3 cups of coffee, the cheapest one is FREE. After asking all his friends for their flavors, Panda wondered how much he need to pay.
Input
The first line of the input gives the number of test cases, T.
T test cases follow. Each test case consists of two lines. The first line contains one integer N, the number of cups to be bought.
The second line contains N integers
p1,p2,⋅⋅⋅,pN
representing the prices of each cup of coffee.
Output
For each test case, output one line containing “Case #x: y”, where x is the test case number (starting from 1) and y is the least amount of money Panda need to pay.
Limits
∙
1 ≤ T ≤ 100.
∙
1 ≤ N ≤
105
.
∙
1 ≤ pi ≤ 1000.
Sample input
2 3 1 2 3 5 10 20 30 20 20
Sample output
Case #1: 5 Case #2: 80题目来源: http://acm.hdu.edu.cn/showproblem.php?pid=5999
思路:贪心策略,首先对价格求和并对价格序列降序排序。然后减去每三个数据中最小的价格。最后即得最小价格。
代码:
#include<stdio.h>
#include<algorithm>
using namespace std;
bool cmp(const int a, const int b)
{
return a > b;
}
int main(void) {
int t, *pri,casee=0;
scanf("%d", &t);
while (t--) {
casee++;
int n,sum=0;
scanf("%d", &n);
pri = new int[n];
for (int i = 0; i < n; i++)
{
scanf("%d", &pri[i]);
sum += pri[i];
}
sort(pri, pri + n, cmp);
if (n < 3) {
printf("Case #%d: %d\n",casee,sum);
continue;
}
for (int i = 2; i < n ; i += 3)
sum -= pri[i];
printf("Case #%d: %d\n", casee, sum);
delete(pri);
}
}
注意:用new开辟的空间要记得用delete删除,否则可能会出现Memory Limit Exceed的情况。