题目:
Problem Description
Lindsay is a shopaholic. Whenever there is a discount of the kind where you can buy three items and only pay for two, she goes completely mad and feels a need to buy all items in the store. You have given up on curing her for this disease, but try to limit its effect on her wallet.
You have realized that the stores coming with these offers are quite elective when it comes to which items you get for free; it is always the cheapest ones. As an example, when your friend comes to the counter with seven items, costing 400, 350, 300, 250, 200, 150, and 100 dollars, she will have to pay 1500 dollars. In this case she got a discount of 250 dollars. You realize that if she goes to the counter three times, she might get a bigger discount. E.g. if she goes with the items that costs 400, 300 and 250, she will get a discount of 250 the first round. The next round she brings the item that costs 150 giving no extra discount, but the third round she takes the last items that costs 350, 200 and 100 giving a discount of an additional 100 dollars, adding up to a total discount of 350.
Your job is to find the maximum discount Lindsay can get.
Input
The first line of input gives the number of test scenarios, 1 <= t <= 20. Each scenario consists of two lines of input. The first gives the number of items Lindsay is buying, 1 <= n <= 20000. The next line gives the prices of these items, 1 <= pi <= 20000.
Output
For each scenario, output one line giving the maximum discount Lindsay can get by selectively choosing which items she brings to the counter at the same time.
Sample Input
1
6
400 100 200 350 300 250
Sample Output
400
题意:有多件商品,每件商品都有价格,每次只要买3件商品,那么最便宜的商品就免费,问买完这些商品最多可以节约多少钱。
其实就是贪心思想:对每件商品的价格按从小到大的顺序排列,然后每次取3的倍数即可。
参考代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 20000+10;
int price[N];
void init() {
memset(price ,0,sizeof(price));
}
int n;
void input() {
for (int i = 0;i < n;++i) {
scanf("%d", &price[i]);
}
}
void quicksort(int price[],int left,int right) {
if (left >= right) return;
int key = price[left];
int i = left,j = right;
while (i < j) {
while (i < j && price[j] >= key) --j;
price[i] = price[j];
while (i < j && price[i] <= key) ++i;
price[j] = price[i];
}
price[i] = key;
quicksort(price,left,i-1);
quicksort(price,i+1,right);
}
void ni() {
for (int i = 0;i < n / 2;++i) {
price[i] = price[i] ^ price[n-1-i];
price[n-1-i] = price[n-1-i] ^ price[i];
price[i] = price[i] ^ price[n-1-i];
}
}
int maxdiscount() {
int sum = 0;
for (int i = 0;i < n;++i) {
if ((i+1) % 3 == 0) {
sum += price[i];
}
}
return sum;
}
int main() {
int t;
scanf("%d", &t);
while (t--) {
init();
scanf("%d", &n);
input();
quicksort(price,0,n-1);
ni();
int sum = maxdiscount();
printf("%d\n", sum);
}
return 0;
}