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

1005. Stone Pile

Time limit: 1.0 second
Memory limit: 64 MB
You have a number of stones with known weights  w 1, …,  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  w 1, …,  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

input output
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的题目很不错,适合进阶者学习。


猜你喜欢

转载自blog.csdn.net/duanghaha/article/details/80303059
今日推荐