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?

ABC014 B - 価格の合計

Posted at

問題

あなたは買い物をしていて,商品リストからいくつかの商品を選んだ.
商品の数,それぞれの商品の価格,そして部分集合を表す10 進整数 X が与えられるので,部分集合に含まれる商品の価格を合計することである.

考察

初めてビット全探索をやる人に向けた問題だと思います。
集合を表す変数が与えられているので、for文の中にfor文を書く必要はありません。

コード

#include <bits/stdc++.h>
#include <atcoder/dsu>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;
using namespace atcoder;

int main() {
    int N, X;
    cin >> N >> X;
    
    int ans = 0;
    
    vector<int> vec(N);
    rep(i, N) cin >> vec[i];
    
    for (int i = 0; i < N; i++) {
        if (X & (1 << i)) {
            ans += vec[i];
        }
    }
    
    cout << ans << endl;
} 

ビット探索の部分はこのように書くこともできます。

#include <bits/stdc++.h>
#include <atcoder/dsu>
#define rep(i, n) for (int i = 0; i < (int)(n); i++)

using namespace std;
using namespace atcoder;

int main() {
    int N, X;
    cin >> N >> X;
    bitset<20> binary(X);
    vector<int> vec(N);
    rep(i, N) cin >> vec[i];
    
    int ans = 0;
    
    for (int i = 0; i < N; i++) {
        if (binary.test(i)) {
            ans += vec[i];
        }
    }
    
    cout << ans << endl;
} 
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?