Time Limit: 4 second(s) | Memory Limit: 32 MB |
Professor Sofdor Ali is fascinated about twin towers. So, in this problem you are working as his assistant, and you have to help him making a large twin towers.
For this reason he gave you some rectangular bricks. You can pick some of the bricks and can put bricks on top of each other to build a tower. As the name says, you want to make two towers that have equal heights. And of course the height of the towers should be positive.
For example, suppose there are three bricks of heights 3, 4 and 7. So you can build two towers of height 7. One contains a single brick of height 7, and the other contains a brick of height 3 and a brick of height 4. If you are given bricks of heights 2, 2, 3 and 4 then you can make two towers with height 4 (just don't use brick with height 3).
Input
Input starts with an integer T (≤ 100), denoting the number of test cases.
Each case starts with an integer n (1 ≤ n ≤ 50), denoting the number of bricks. The next line contains n space separated integers, each containing the height of the brick hi (1 ≤ hi ≤ 500000). You can safely assume that the sum of heights of all bricks will not be greater than 500000.
Output
For each case, print the case number and the height of the tallest twin towers that can be built. If it's impossible to build the twin towers as stated, print "impossible".
Sample Input | Output for Sample Input |
4 3 3 4 7 3 10 9 2 2 21 21 9 15 15 14 24 14 3 20 23 15 | Case 1: 7 Case 2: impossible Case 3: 21 Case 4: 64 |
dp[i][j] 代表前i个数形成 差为j 的较大数的最大值
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hihi\n")
#define eps 1e-12
typedef __int64 ll;
using namespace std;
#define INF 0x3f3f3f3f
#define N 500005
int dp[2][N];
int a[55];
int n;
int all;
void DP()
{
int i,j;
memset(dp,-1,sizeof(dp));
dp[0][0]=0;
int cur,to;
cur=0;
for(i=1;i<=n;i++)
{
int to=cur^1;
memset(dp[to],-1,sizeof(dp[to]));
for(int d=0;d+a[i]<=all;d++)
{
if(dp[cur][d]<0) continue;
dp[to][d]=max(dp[to][d],dp[cur][d]);
dp[to][d+a[i]]=max(dp[to][d+a[i]],dp[cur][d]+a[i]);
if(d>=a[i]) dp[to][d-a[i]]=max(dp[to][d-a[i]],dp[cur][d]);
else dp[to][a[i]-d]=max(dp[to][a[i]-d],dp[cur][d]+a[i]-d);
}
cur^=1;
}
if(dp[cur][0]<=0)
printf("impossible\n");
else
printf("%d\n",dp[cur][0]);
}
int main()
{
int i,j,t,ca=0;
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
all=0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
all+=a[i];
}
printf("Case %d: ",++ca);
DP();
}
return 0;
}
/*
4
3
3 4 7
3
10 9 2
2
21 21
9
15 15 14 24 14 3 20 23 15
*/