Title Description
Xiao Ming is like to put the building blocks, and now he is playing with building blocks of N block is composed of two towers Dachu he wanted to use these pieces of wood the same height, the height of a tower is built of wood in all its height and and use at least one of a tower block. Each block can only be used once, can not. Now known height of each piece of wood, Xiao Ming would like to know in the case of the same final height of two towers, he can take the maximum height of the tower is how much, can you help him?
Input Format
Conduct a first integer N, the number of the block.
The second line is the N integers, N represents the height of the block of wood.
[Data] scale
To 100% of the data, N≤50, the height h of each block satisfies 1≤h≤500000, the sum of the height of the block ≤500000 all.
Output Format
Only an integer representing the maximum height of the tower can be built, if not the same height two column structures, outputs "-1."
Sample input and output
3 2 3 5
5
Solution: I think a little about the DP title, f [i] [j] is selected to represent the i-th blocks,
Tad two difference is shorter height at j, push to
#include<cstdio> #include<iostream> #include<cmath> #include<cstring> #include<cstdlib> #include<algorithm> #include<queue> using namespace std; const int N=55; int n,a[N],sum; int f[51][500001]; int main(){ freopen("1284.in","r",stdin); freopen("1284.out","w",stdout); scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&a[i]); sum+=a[i]; } sum/=2; memset(f,-3,sizeof(f)); f[0][0]=0; for(int i=1;i<=n;i++){ for(int j=sum;j>=0;j--){ f[i][j]=max(f[i-1][j],f[i-1][j+a[i]]); if(j>=a[i]) f[i][j]=max(f[i][j],f[i-1][j-a[i]]+a[i]); else f[i][j]=max(f[i][j],f[i-1][a[i]-j]+j); } } if(f[n][0]<=0) puts("-1\n"); else printf("%d\n",f[n][0]); return 0; }