LoginSignup
i_rei
@i_rei

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

AtCoderのC問題でRE(実行時エラー)の原因がわからない

解決したいこと

AtCoderのABC229のC問題「Cheese」を解いていました。
提出すると、いくつかのケースのみ「RE」(実行時エラー)となってしまいました(19個がAC、3個がRE)。

なぜREになってしまうのか、教えていただけると幸いです。

自分でも考えてみましたが、わかりませんでした。

問題のリンク

該当するソースコード

n, w = map(int, input().split())
cheese = dict()
for i in range(n):
    a, b = map(int, input().split())
    if a in cheese:
        cheese[a] += b
    else:
        cheese[a] = b
c = sorted(cheese)
c.reverse()

rd = 0 #最終的に出力します
i = 0
while w > 0 and i < n:
    a = c[i]
    if w - cheese[a] == 0:
        rd += a * cheese[a]
        w -= cheese[a]
        print(rd)
        exit()
    elif w - cheese[a] > 0:
        rd += a * cheese[a]
        w -= cheese[a]
    else: # w - cheese[a] < 0
        rd += a * w
        print(rd)
        exit()
    i += 1
print(rd)

このコードよりも効率的な書き方があるのは承知していますが、このコードのエラーの原因を知りたいのでよろしくお願いします。

0

3Answer

Comments

  1. @i_rei

    Questioner
    テストファイルが公開されているのは知らなかったです。どうもありがとうございます。

Comments

  1. @i_rei

    Questioner
    エラーが分かりました。ありがとうございます。

美味しさが同じ値のケースだと、チーズの種類Nよりユニークなcの数が減るからですね。

while w > 0 and i < len(c):

にすれば直るんじゃないでしょうか

0

Comments

  1. @i_rei

    Questioner
    ありがとうございます。無事ACになりました。

Your answer might help someone💌