3
1

N, M = map(int, input().split())

MARKET = [(lambda item, price: (item, int(price))
            )(*input().split())
            for _ in range(N)
            ]
WANTEDS = [input() for _ in range(M)]

for w in WANTEDS:
    print(
        sum(price for item, price in MARKET
            if item.startswith(w)
            )
        )

市場のものと欲しいものをそれぞれ読み込み、欲しいもの毎にそれで始まる文字列の値段を集計する。
これだとタイムアウトしそうだが、結構余裕でクリアーだったのだが?

解答例を見ると、入力をうけとった時点で100文字までの全てのprefixの可能性に対して集計するっていうものでした。まぢか...
そっちの方向性でやってみる。

N, M = map(int, input().split())

amountdict = {}

for _ in range(N):
   item, price = ( lambda i, p: (i, int(p))
                  )(*input().split())
   
   prefix = ""
   
   for i in range(min(100, len(item))):
       if (prefix := prefix + item[i]) in amountdict:
           amountdict[prefix] += price
       else:
           amountdict[prefix] = price

for _ in range(M):
   print(amountdict[prefix]
         if (prefix := input()) in amountdict
         else 0
         )

だいぶ速くなりました。なるほどね。勉強になりました。

3
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
1