ZOJ2059The Twin Towers题解动态规划DP

The Twin Towers

Time Limit: 1 Second      Memory Limit: 32768 KB

Twin towers we see you standing tall, though a building's lost our faith will never fall.
Twin towers the world hears your call, though you're gone it only strengthens our resolve.
We couldn't make it through this without you Lord, through hard times we come together more. ...

Twin Towers - A Song for America

In memory of the tragic events that unfolded on the morning of September 11, 2001, five-year-old Rosie decids to rebuild a tallest Twin Towers by using the crystals her brother has collected for years. Will she succeed in building the two towers of the same height?


Input

There are mutiple test cases.

One line forms a test case. The first integer N (N < 100) tells you the number of crystals her brother has collected. Then each of the next N integers describs the height of a certain crystal.

A negtive N indicats the end.

Note that all crytals are in cube shape. And the total height of crystals is smaller than 2000.


Output

If it is impossible, you would say "Sorry", otherwise tell her the height of the Twin Towers.


Sample Input

4 11 11 11 11
4 1 11 111 1111
-1


Sample Output

22
Sorry

 

 

状态:

d[i][j]前i个组成两座高度差为j的低塔德最大高度

 

状态转移方程:

 

 一共用两种放法,产生三种情况

放在高塔上

放在低塔上:1。低塔仍是低塔2.低塔超过高塔

     x=d[i-1][j];
     y=d[i-1][j]+j;
     if(y>=x+a[i])//放在低塔上
     {
      if(d[i][j-a[i]]<=x+a[i])
       d[i][j-a[i]]=x+a[i];
     }
     else
     {
      if(d[i][a[i]-j]<y)//低塔超过高塔
       d[i][a[i]-j]=y;
     }
     if(d[i][j+a[i]]<x)//放在高塔上
      d[i][j+a[i]]=x;

 

边界:

d[0][0]=0

others -1

 

代码:

 

 #include<cstdio> #include<cstring> #include<cstdlib> int main() { int n,i,j,x,y,a[105],d[105][2005];//前i个组成高度差为j的低塔高度 while(scanf("%d",&n),n>=0) { if(n<=1) { puts("Sorry"); continue; } memset(d,-1,sizeof(d)); d[0][0]=0; for(i=1;i<=n;i++) scanf("%d",a+i); for(i=1;i<=n;i++) { memcpy(d[i],d[i-1],sizeof(d[i]));//不放第i个 for(j=0;j<=2000;j++) { if(d[i-1][j]!=-1) { x=d[i-1][j]; y=d[i-1][j]+j; if(y>=x+a[i])//放在低塔上 { if(d[i][j-a[i]]<=x+a[i]) d[i][j-a[i]]=x+a[i]; } else { if(d[i][a[i]-j]<y)//低塔超过高塔 d[i][a[i]-j]=y; } if(d[i][j+a[i]]<x)//放在高塔上 d[i][j+a[i]]=x; } } } if(d[n][0]) printf("%d/n",d[n][0]); else puts("Sorry"); } }

你可能感兴趣的:(ZOJ2059The Twin Towers题解动态规划DP)