【问题标题】:Google kickstart 2020 round A wrong answerGoogle kickstart 2020 round A 错误答案
【发布时间】:2020-10-18 19:04:21
【问题描述】:

问题链接:https://codingcompetitions.withgoogle.com/kickstart/round/000000000019ffc7/00000000001d3f56

问题 有 N 栋房屋待售。第 i 间房子花费 Ai 美元购买。你有 B 美元的预算要花。 最多可以买几套房子?

输入 输入的第一行给出了测试用例的数量,T.T 测试用例紧随其后。每个测试用例都以包含两个整数 N 和 B 的单行开始。第二行包含 N 个整数。第 i 个整数是 Ai,即第 i 个房子的成本。

输出 对于每个测试用例,输出一行包含 Case #x: y,其中 x 是测试用例编号(从 1 开始),y 是您可以购买的最大房屋数。

**Limits**
Time limit: 15 seconds per test set.
Memory limit: 1GB.
1 ≤ T ≤ 100.
1 ≤ B ≤ 105.
1 ≤ Ai ≤ 1000, for all i.

**Test set 1**
1 ≤ N ≤ 100.

**Test set 2**
1 ≤ N ≤ 105.

**Sample Input** 
3
4 100
20 90 40 90
4 50
30 30 10 10
3 300
999 999 999

**Sample Output**  
Case #1: 2
Case #2: 3
Case #3: 0

在示例案例 #1 中,您的预算为 100 美元。您可以花 20 + 40 = 60 美元购买 1 号和 3 号房屋。 在示例案例 #2 中,您的预算为 50 美元。您可以花 30 + 10 + 10 = 50 美元购买第 1、第 3 和第 4 套房屋。 在示例案例 #3 中,您的预算为 300 美元。你不能买任何房子(所以答案是0)。

这是我的解决方案(Python 3):

T = int(input())

res = []
for i in range(T):
    N, B = map(int, input().split(' '))
    ai = list(map(int, input().split(' ')))
    ai.sort()
    for k in range(len(ai)):
        B = B - ai[k]
        if B < 0:
            res.append(k)
            break
        elif k == len(ai)-1:
            res.append(k+1)

for i in range(T):
    print("Case #", i+1, ":", res[i])

我已经尝试了所有我能想到的测试用例,并且得到了预期的输出。但是当我尝试提交时,它显示 Sample Failed: wrong answer。请让我知道我的解决方案到底出了什么问题以及如何改进它。

【问题讨论】:

  • 是否允许其他人为您编写正确的解决方案?如果是跑步比赛,那我想没关系,否则不是。是吗?
  • 规范说输出格式为"Case #3 : 2",但您的输出格式为"Case # 3 : 2"。那会不会绊倒你?

标签: python python-3.6


【解决方案1】:

我认为问题出在您最后的打印语句中,您有:

>>> print("Case #", i+1, ":", res[i])
Case # 0 : 2

请注意,“#”之后和“:”之前有一个额外的空格,而不是比赛指定的空格。试试:

>>> print("Case #", i+1, ": ", res[i], sep="")
Case #0: 2

【讨论】:

  • 另外,你能告诉我是否有办法改进这段代码吗?
【解决方案2】:

我建议稍微简化您的代码并确保使用字符串格式。如果是 python 3.6 及更高版本,您可以使用 f-string 或使用 string.format

# your second for loop
counter = 0
for k in ai:
    if B - k >= 0:
        B -= k
        counter += 1
    else:
        res.append(counter)
        break

for i in range(len(res)):
    # using f-string
    print(f"Case #{i+1}: {res[i]}")
    # using string format
    print("Case #{}: {}".format(i+1, res[i]))

【讨论】:

    【解决方案3】:

    Python 3 中的这个解决方案

    n = int(input())
    h = []
    for i in range(n):
        N, B = map(int,input().split())
        B = int(B)
        d = []
        a = 0
        n = sorted(list(map(int,input().split()[:N])))
        for j in n:
            if j <= B:
                B = B-j
                a+=1
        h.append("Case #{}: {}".format(i+1,a))
    for i in h:
    print(i)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      • 2020-12-14
      相关资源
      最近更新 更多