#include<bits/stdc++.h>
using namespace std;
int knapsack(int wt, int v[], int w[], int n)
{
int t[n+1][wt+1], i, j;
for(i=0; i<=n; i++)
{
for(j=0; j<=wt; j++)
{
if(i == 0 || j == 0)
t[i][j] = 0;
else if(w[i-1] <= j)
t[i][j] = max((v[i-1]+t[i-1][j-w[i-1]]), t[i-1][j]);
else
t[i][j] = t[i-1][j];
}
}
return t[n][wt];
}
int main()
{
int n, t;
cin >> t;
while(t--)
{
cin >> n;
int v[n], w[n], wt, i, tk, sum = 0;
for(i=0; i<n; i++)
{
cin >> tk;
sum += tk;
v[i] = w[i] = tk;
}
wt = sum/2;
int p = knapsack(wt, v, w, n);
cout << sum - 2*p << "\n";
}
return 0;
}
using namespace std;
int knapsack(int wt, int v[], int w[], int n)
{
int t[n+1][wt+1], i, j;
for(i=0; i<=n; i++)
{
for(j=0; j<=wt; j++)
{
if(i == 0 || j == 0)
t[i][j] = 0;
else if(w[i-1] <= j)
t[i][j] = max((v[i-1]+t[i-1][j-w[i-1]]), t[i-1][j]);
else
t[i][j] = t[i-1][j];
}
}
return t[n][wt];
}
int main()
{
int n, t;
cin >> t;
while(t--)
{
cin >> n;
int v[n], w[n], wt, i, tk, sum = 0;
for(i=0; i<n; i++)
{
cin >> tk;
sum += tk;
v[i] = w[i] = tk;
}
wt = sum/2;
int p = knapsack(wt, v, w, n);
cout << sum - 2*p << "\n";
}
return 0;
}
Comments
Post a Comment