题目链接
题目描述
小红的购物车里有 件商品。对于每件商品,我们知道它的价格以及小红是否选择购买它。
如果选择购买,会用字符 'O' 标记;如果不购买,则用 'X' 标记。
需要计算所有标记为 'O' 的商品的总价格。
解题思路
这是一个基础的模拟题,我们只需要按照题目的描述,逐步累加所有被选中商品的价格即可。
具体的算法步骤如下:
-
初始化一个用于累计总金额的变量
total_cost
为 0。为了防止总金额过大而溢出,最好使用 64 位整型(如 C++ 的long long
或 Java 的long
)。 -
读取商品的总数量
。
-
循环
次,每次处理一件商品:
a. 读取该商品的价格
price
和选择标记choice
。b. 判断
choice
字符是否为 'O'。c. 如果是 'O',则将
price
加到total_cost
上。 -
循环结束后,输出
total_cost
的值即可。
代码
#include <iostream>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
int n;
cin >> n;
long long total_cost = 0;
for (int i = 0; i < n; ++i) {
int price;
char choice;
cin >> price >> choice;
if (choice == 'O') {
total_cost += price;
}
}
cout << total_cost << endl;
return 0;
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long totalCost = 0;
for (int i = 0; i < n; i++) {
int price = sc.nextInt();
String choice = sc.next();
if (choice.equals("O")) {
totalCost += price;
}
}
System.out.println(totalCost);
}
}
import sys
def solve():
try:
n_str = sys.stdin.readline().strip()
if not n_str: return
n = int(n_str)
total_cost = 0
for _ in range(n):
line = sys.stdin.readline().strip().split()
price = int(line[0])
choice = line[1]
if choice == 'O':
total_cost += price
print(total_cost)
except (IOError, ValueError):
return
solve()
算法及复杂度
-
算法:模拟
-
时间复杂度:
,其中
是商品的数量。我们只需要遍历一次所有商品。
-
空间复杂度:
。我们只需要常数级别的额外空间来存储总金额和单次循环中的变量。