洛谷 P2415 集合求和 题解 C/C++

思路如下:

  • 找规律:例如集合s为{1, 2, 3, 4, 5,…}, 我们这里以元素1为例,统计每个元素出现的次数,子集为一个元素时,是{1},子集为两个元素时,是{1, 2}、{1, 3}、{1, 4}、{1, 5}…,子集为三个元素时,是{1, 2, 3}、{1, 2, 4}、{1, 2, 5},…,子集为4个元素时…;
  • 联系排列组合的知识,也就是说:选中一个元素,从剩余n-1个元素中取0个,1个,2个,3个,…组成子集,每个元素出现的总次数是一样的,最后每个元素出现的总次数公式如下:
    C n − 1 0 + C n − 1 1 + C n − 1 2 + C n − 1 3 + . . . = 2 n − 1 \mathrm{C}_{n-1}^0+{C}_{n-1}^1+{C}_{n-1}^2+{C}_{n-1}^3+... = 2^{n-1} Cn10+Cn11+Cn12+Cn13+...=2n1
  • 最终结果就是集合s各元素之和乘以 2 n − 1 2^{n-1} 2n1
//P2415 集合求和
//#define LOCAL
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <cmath>
#include <algorithm>
#include <cctype>
#include <sstream>
#define inf 0x3f3f3f3f
#define eps 1e-6
using namespace std;
#define clr(x) memset(x,0,sizeof((x)))
const int maxn = 1e5+1;//2e6+1
#define MAX(a,b,c) ((a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c)))
#define _max(a,b) ((a) > (b) ? (a) : (b))
#define _min(a,b) ((a) < (b) ? (a) : (b))
#define _for(a,b,c) for(int a = b;a<c;a++)
typedef long long ll;
int main()
{
    
    
#ifdef LOCAL 
	freopen("data.in","r",stdin);
	freopen("data.out","w",stdout);
#endif
	int n,i = 0;
	ll ans = 0;
	while(scanf("%d",&n)==1) {
    
    
		ans+=n;
		i++;
	}
	cout<<ans*(1<<(i-1));
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Jason__Jie/article/details/113132226