牛客题解 | 买面包
题目
解题思路
这是一道简单的购物计算题目,主要思路如下:
- 
数据存储: - 使用数组存储每种面包的价格
- 使用结构体存储购买记录(面包种类和数量)
 
- 
计算步骤: - 读入面包种类数n和每种面包的价格
- 读入购买记录数m
- 读入m条购买记录
- 根据每条记录计算总价
 
- 
注意事项: - 数组下标从0开始,而输入的面包种类从1开始
- 需要使用long类型存储总价,防止溢出
 
代码
#include <iostream>
using namespace std;
struct Purchase {
    int type;  // 面包种类
    int count; // 购买数量
};
int main() {
    int n;
    cin >> n;
    
    // 读入每种面包的价格
    int prices[101] = {0};
    for(int i = 0; i < n; i++) {
        cin >> prices[i];
    }
    
    // 读入购买记录数
    int m;
    cin >> m;
    
    // 计算总价
    long total = 0;
    for(int i = 0; i < m; i++) {
        int type, count;
        cin >> type >> count;
        total += prices[type-1] * count;
    }
    
    cout << total << endl;
    return 0;
}
import java.util.Scanner;
public class Main {
    static class Purchase {
        int type;  // 面包种类
        int count; // 购买数量
        
        Purchase(int type, int count) {
            this.type = type;
            this.count = count;
        }
    }
    
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        
        // 读入面包种类数
        int n = sc.nextInt();
        
        // 读入每种面包的价格
        int[] prices = new int[101];
        for(int i = 0; i < n; i++) {
            prices[i] = sc.nextInt();
        }
        
        // 读入购买记录数
        int m = sc.nextInt();
        
        // 计算总价
        long total = 0;
        for(int i = 0; i < m; i++) {
            int type = sc.nextInt();
            int count = sc.nextInt();
            total += prices[type-1] * count;
        }
        
        System.out.println(total);
    }
}
n = int(input())
jiage = list(map(int,input().split()))
m = jiage[-1]
summary = 0
for i in range(m):
    num = list(map(int,input().split()))
    summary += jiage[num[0]-1]*num[1]
print(summary)
算法及复杂度
- 算法:简单遍历计算
- 时间复杂度:\(\mathcal{O}(m)\) - 其中 \(m\) 为购买记录数
- 空间复杂度:\(\mathcal{O}(n)\) - 其中 \(n\) 为面包种类数
 
                    
                
 
 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号