Divide a bunch of positive integers into 2 groups, and require the sum of the 2 groups to have the smallest difference.
For example: 1 2 3 4 5, 1 2 4 is divided into 1 group, 3 5 is divided into 1 group, the difference between the two groups is 1, which is the least difference among all the schemes.
Input
Line 1: A number N, where N is the number of positive integers. Lines 2 - N+1, N positive integers. (N <= 100, sum of all positive integers <= 10000)
Output
output this minimum difference
Input example
5 1 2 3 4 5
Output example
1
#include <iostream> #include <algorithm> #include <cstring> #include <cstdio> #include <vector> #include <queue> #include <stack> #include <cstdlib> #include <iomanip> #include <cmath> #include <cassert> #include <ctime> #include <map> #include <set> using namespace std; #pragma comment(linker, "/stck:1024000000,1024000000") #define lowbit(x) (x&(-x)) #define max(x,y) (x>=y?x:y) #define min(x,y) (x<=y?x:y) #define MAX 100000000000000000 #define MOD 1000000007 #define pi acos(-1.0) #define ei exp(1) #define PI 3.1415926535897932384626433832 #define ios() ios::sync_with_stdio(true) #define INF 0x3f3f3f3f #define mem(a) ((a,0,sizeof(a))) typedef long long ll; int dp[10006],a[106],n; int ans=0,pos; int main() { scanf("%d",&n); for(int i=0;i<n;i++) { scanf("%d",&a[i]); years += a[i]; } memset(dp,0,sizeof(dp)); pos=ans/2; for(int i=0;i<n;i++) { for(int j=pos;j>=a[i];j--) dp[j]=max(dp[j],dp[j-a[i]]+a[i]); } int cnt=0; for(int i=0;i<=pos;i++) cnt=max(cnt,dp[i]); //printf("%d\n",cnt); printf("%d\n",abs(ans-cnt-cnt)); return 0; }