算法笔记-第四章简单贪心题解
背景
目前算法笔记的学习已经进展到第四章,下面会记录第四章贪心算法的两道题解。写这篇博客的目的也是鼓励自己继续学习下去。
简单贪心
PAT B1020
#include <stdio.h>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <cmath>
using namespace std;
struct Mooncake {
double store;//库存量,单位万吨
double saleprice;//总售价,单位亿元
double perStorePrice;//总售价/库存量,单价
} mooncake[1000];
bool cmpMoon(Mooncake a, Mooncake b) {
//单价高的排在前面
return a.perStorePrice > b.perStorePrice;
}
/**
* 贪心算法,月饼题目
*/
int main() {
int moonTypes = 0, maxCommand = 0;
scanf("%d%d", &moonTypes, &maxCommand);
for (int i = 0; i < moonTypes; ++i) {
scanf("%lf", &mooncake[i].store);
}
for (int i = 0; i < moonTypes; ++i) {
scanf("%lf", &mooncake[i].saleprice);
mooncake[i].perStorePrice = mooncake[i].saleprice / mooncake[i].store;
}
sort(mooncake, mooncake + moonTypes, cmpMoon);
double sum = 0;
int remainingCommand = maxCommand;
for (int i = 0; i < moonTypes; ++i) {
if (remainingCommand <= mooncake[i].store) {
sum += remainingCommand * mooncake[i].perStorePrice;
printf("%.2f", sum);
break;
} else {
sum += mooncake[i].saleprice;
remainingCommand = remainingCommand - mooncake[i].store;
if (i == moonTypes - 1) {
printf("%.2f", sum);
break;
}
}
}
return 0;
}
PAT B1023
#include <stdio.h>
int minNumber[50] = {};
int main(){
int numCount[10] = {0};
//总字符个数
int sum = 0;
bool initialflag = false;
for (int i = 0; i < 10; ++i) {
scanf("%d", &numCount[i]);
if (numCount[i] > 0) {
sum += numCount[i];
}
//找到非0的第一个首位
if (i >= 1 && numCount[i] > 0 && !initialflag) {
minNumber[0] = i;
numCount[i] = numCount[i] - 1;
initialflag = true;
}
}
//遍历,拼接字符
int minTotalCode = 1;
for (int i = 0; i < 10; ++i) {
if (numCount[i] != 0) {
for (int j = 0; j < numCount[i]; ++j) {
minNumber[minTotalCode] = i;
minTotalCode++;
}
}
}
for (int i = 0; i < sum; ++i) {
printf("%d", minNumber[i]);
}
return 0;
}