0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paizaラーニング問題集「【全探索 2】コップの水」を、解説例に基づいて解いてみた

Posted at

▼解説例の考え方

bit全探索と呼ばれる手法を使用すると、すべての小さなコップの組合せを求めることができます。以下に概要を示します。

image.png

▼コード

########## 処理0(準備) インプット,リスト定義 ###########

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

w = [0]*N
for i in range(N):
    w[i] = int(input())

# max_ml: 大きなコップに入れられる水の最大量を格納する変数
max_ml = 0

# max_ml: 小さなコップの組合せたときの、水の合計量
tmp_ml = 0

########## 処理1 小さなコップの組合せたときの水の合計量のうち、大きなコップの容量を超えない最大値を求める ###########

for i in range(2**N):

    for j in range(N):
        if (i>>j)&1:
            tmp_ml += w[j]
        
    if tmp_ml <= K and max_ml < tmp_ml:
        max_ml = tmp_ml
    
    tmp_ml = 0

print(max_ml)

▼参考
以下は、本問を解説例ではなく、私の考え方に基づいて解いてみた記事です。
https://qiita.com/toytoy24/items/bc3682a32442ec593e60

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?