【Atcoder agc020 C】Median Sum,序列子集和中位数,bitset,01背包

problem

C - Median Sum / Time Limit: 2 sec / Memory Limit: 512 MB Score : 700 points Problem Statement

You are given N integers A 1 , A 2 , …, A N . Consider the sums of all non-empty subsequences of A . There are 2 N − 1 such sums, an odd number. Let the list of these sums in non-decreasing order be S 1 , S 2 , …, S 2 N − 1 . Find the median of this list, S 2 N − 1 . Constraints 1 ≤ N ≤ 2000 1 ≤ A i ≤ 2000 All input values are integers.

C-中位数/时间限制:2秒/内存限制:512 MB得分:700分问题陈述

给您N个整数A 1,A 2,…,A N。 考虑A的所有非空子序列的总和。 这样的和有2 N-1个,一个奇数。 令这些和以非降序排列的列表为S 1,S 2,…,S 2 N -1。 找到该列表的中位数S 2 N − 1。 约束1≤N≤2000 1≤A i≤2000所有输入值都是整数。

input:
3
1 2 1

output:
2

solution
/*
Atcoder,  agc020_c
题意:
+ 给出一个长为n的序列,考虑所有(2^n-1)个非空子序列的和
+ 令这些和升序排列,输出它们的中位数。
思路:
+ 将序列等价于集合S,子序列就是非空子集A。对于每个A,它的补集要么是空集,要么也在S中。
+ 将两个互补的子集看做一组,那么每组中至少一个子集>=sum/2,另一个子集<=sum/2。
+ 所以这个序列的中位数就是第一个大于等于sum/2的子集,所以可以用01背包来解。
+ 因为V=4e6,N=2e3,VN=8e9,会超时,因为是二进制所以可以用bitset优化。因为dp[i]=max(dp[i],dp[i-ai]),所以左移的操作就可以做到这个目的。
+ 比如101011,ai=3,101011<<3=101011000,101011000|101011=10111011就相当于用ai更新了一次。
*/
#include<bits/stdc++.h>
using namespace std;
const int maxn = 4e6+10;
bitset<maxn>b;
int main(){
	int n;  cin>>n;
	int sum = 0;
	vector<int>a(n);
	for(int i = 0; i < n; i++){
		cin>>a[i];  sum += a[i];
	}
	
	b[0] = 1;
	for(int i = 0; i < n; i++)
		b |= (b<<a[i]);
	
	int ans = sum+1>>1;
	while(b[ans]==0)ans++;
	cout<<ans<<"\n";
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小哈里

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值