Solution Idea

50056. How Much Money Can You Make?

這題需要的一些技巧:

  1. 找出最大值(最大獲利), 與最小值(原料可生產的商品數)。
  2. 字串比較 strcmp() 函式,透過字串比較得到該原物料的索引值來對映至原料的數量及單位價格。
  3. 當有多個最大獲利相同的商品時,我們同樣透過 strcmp() 函示來找出字典序最小的商品名子來當作輸出。

比較兩個字串 str1 與 str2
ret = strcmp( str1, str2 );
傳回值為一個整數 ret
ret < 0 時代表 str1 比 str2 的字典序還小
ret == 0 時代表兩個字串是相同的
ret > 0 時代表 str1 比 str2 的字典序還大

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define INT_MIN -2147483648
#define INT_MAX 2147483647
 
int main(){
    int N, M, K, i, j, maxProfit = INT_MIN, maxProfitProductIndex = 0;
    char materialsName[128][64];
    char productsName[128][64];
    int materialsAmount[128];
    int materialsUnitPrice[128];
 
    scanf("%d %d", &N, &M);
    for( i = 0 ; i < N ; ++i )
        scanf("%s %d %d", materialsName[i], &materialsAmount[i], &materialsUnitPrice[i]);
 
    for( i = 0 ; i < M ; ++i ){
        int productsPrice = 0, profit = 0, maxProductAmount = INT_MAX, productCost = 0;
        scanf("%s %d", productsName[i], &K);
        for( j = 0 ; j < K ; ++j){
            char ingredientName[64];
            int ingredientNeed, index = 0, productAmount = 0;
            scanf("%s %d", ingredientName, &ingredientNeed);
            while( strcmp(ingredientName, materialsName[index]) != 0 )
                ++index;
            productAmount = materialsAmount[index] / ingredientNeed;
            if( productAmount < maxProductAmount )
                maxProductAmount = productAmount;
            productCost += materialsUnitPrice[index] * ingredientNeed;
        }
        scanf("%d", &productsPrice);
        profit = (productsPrice - productCost) * maxProductAmount;
        if(profit > maxProfit){
            maxProfit = profit;
            maxProfitProductIndex = i;
        }
        else if(profit == maxProfit){
            if( strcmp(productsName[i], productsName[maxProfitProductIndex]) < 0 ){
                maxProfitProductIndex = i;
            }
        }
    }
    printf("%s %d\n", productsName[maxProfitProductIndex], maxProfit);
 
    return 0;
}

Discussion