P2415 集合求和

题目传送门

#include<bits/stdc++.h>

using namespace std;
typedef long long LL;
const int N = 110;
LL a[N];
int n;
LL res;

int main() {
    //录入进来,终止条件是CTRL+D
    while (cin >> a[++n]);
    n--;
    //找规律
    /**
     2,3
     元素个数n=2
     [2][3]
     [2,3]
     2出现2次,3出现2次。就元素都出现2^1次。

     2,3,4
     元素个数n=3
     [2][3][4]
     [2,3][2,4][3,4]
     [2,3,4]
     2出现4次,3出现4次,4出现4次,就元素都出现2^2次。

     发现规律:
     任意元素出现2^(n-1)次!
     */

    //暴力版本
    //for (int i = 1; i <= n; i++)res += a[i] * pow(2, n - 1);

    //位运算优化版本
    for (int i = 1; i <= n; i++)res += a[i] * (1 << (n - 1));
    /**
     C++中int和long long特别容易被忽略的点,在做乘法的时候即使单个变量在int范围内,如果乘积超了int,
     也需要将乘数定义为long long 否则会出错
     https://www.cnblogs.com/littlehb/p/14977432.html
     */
    cout << res << endl;
    return 0;
}
原文地址:https://www.cnblogs.com/littlehb/p/15575740.html