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 |
给你一些砖头的高度,让你建两座高度相同的塔,如果不能建成,则输出impossible。
dp[i][j]表示选到第i块砖头,两座塔高度的差值为j。因为高度最高为50W,砖头的数量最多为50,如果开2500W的数组,那么就超内存了,所以只能用滚动数组了。
加砖头的时候,可以加到高的塔上,也可以加到低的塔上,加到低的塔上的时候又分两种情况,一个是两塔的高度差大于砖头的高度时,差变小了,另一种是两塔的高度差小于砖头的高度,那么低的塔加上砖头后高度就比原先高的塔要高了。具体看代码。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define inf 1e9
#define endl '\n'
#define LL long long
using namespace std;
int dp[2][500050];
int main(void)
{
int T,n,i,j;
int a[55];
scanf("%d",&T);
int cas = 1;
while(T--)
{
scanf("%d",&n);
int sum = 0;
for(i=1;i<=n;i++)
{
scanf("%d",&a[i]);
sum += a[i];
}
sum /= 2;
memset(dp,-1,sizeof(dp));
dp[0][0] = 0;
int s = 1;
for(i=1;i<=n;i++)
{
s ^= 1;
for(j=0;j<=sum;j++)
{
dp[s^1][j] = max(dp[s][j],dp[s^1][j]);
if(dp[s][j] == -1)
continue;
if(j+a[i] <= sum)
dp[s^1][j+a[i]] = max(dp[s^1][j+a[i]],dp[s][j] + a[i]);
if(j >= a[i])
dp[s^1][j-a[i]] = max(dp[s^1][j-a[i]],dp[s][j]);//最高的塔的高度不变
else
dp[s^1][a[i]-j] = max(dp[s^1][a[i]-j],dp[s][j] + a[i] - j);//这里注意低的塔的高度变高了
}
}
printf("Case %d: ",cas++);
if(dp[s^1][0]==0)
printf("impossible\n");
else
printf("%d\n",dp[s^1][0]);
}
}