【ural oj 1005】Stone Pile(01背包)

本文介绍了一种解决石头堆分成两组时重量差最小的问题,通过计算总重量的一半并使用01背包算法来确定最接近该值的组合,从而得出最小差值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1005. Stone Pile

Time limit: 1.0 second
Memory limit: 64 MB
You have a number of stones with known weights w1, …, wn. Write a program that will rearrange the stones into two piles such that weight difference between the piles is minimal.

Input

Input contains the number of stones n (1 ≤ n ≤ 20) and weights of the stones w1, …, wn (integers, 1 ≤ wi≤ 100000) delimited by white spaces.

Output

Your program should output a number representing the minimal possible weight difference between stone piles.

Sample

inputoutput
5
5 8 13 27 14
3

提议就是给你一组数据,让你把他们分成两半,使得这两部分的差值最小,我们可以先把总价值求出来,然后把价值除于二,然后直接01背包走一遍看看空间最大为总价值一半的时候最多能拿多少价值的东西,然后直接相减即可;

AC 代码:

#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
#define MAXN 10000000
int dp[MAXN];
int a[MAXN];

int main()
{
	int n;
	while(cin>>n)
	{
		int ans=0;
		for(int i=0;i<n;i++)
		{
			cin>>a[i];
			ans+=a[i];
		}
		int sum=ans/2;
		memset(dp,0,sizeof(dp));
		for(int i=0;i<n;i++)
		{
			for(int j=sum;j>=a[i];j--)
			{
				dp[j]=max(dp[j],dp[j-a[i]]+a[i]);
			}
		}
		cout<<ans-dp[sum]*2<<endl;
	}
	return 0;
}

突然发现ural oj的题目很不错,适合进阶者学习。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值