1. 程式人生 > 實用技巧 >演算法筆記-第四章簡單貪心題解

演算法筆記-第四章簡單貪心題解

背景

目前演算法筆記的學習已經進展到第四章,下面會記錄第四章貪心演算法的兩道題解。寫這篇部落格的目的也是鼓勵自己繼續學習下去。

簡單貪心

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;
}