SCU 4512 Goozy的积木(dp)

题目传送门:http://acm.scu.edu.cn/soj/problem.action?id=4512
搭建双子塔,因为n只有50,但是高度有50W,所以第一维需要滚动掉,然后如何考虑状态呢, dp[|hAhB|]= ,最后只需要 dp[0]/2 即可,转移的时候就是能减就减,能加就加,还有一个就是如果当前 |hAhB| 比当前的 hi 小,但是也能减,就是高度差变成 hi|hAhB| ,这一点不能忘记,当时错了好久。

代码:

#include <map>
#include <set>
#include <stack>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <cstdio>
#include <cctype>
#include <cstring>
#include <sstream>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#pragma comment(linker,"/STACK:102400000,102400000")

using namespace std;
#define MAX 500005
#define MAXN 1000005
#define maxnode 15
#define sigma_size 30
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define lrt rt<<1
#define rrt rt<<1|1
#define middle int m=(r+l)>>1
#define LL long long
#define ull unsigned long long
#define mem(x,v) memset(x,v,sizeof(x))
#define lowbit(x) (x&-x)
#define pii pair<int,int>
#define bits(a) __builtin_popcount(a)
#define mk make_pair
#define limit 10000

//const int prime = 999983;
const int    INF   = 0x3f3f3f3f;
const LL     INFF  = 0x3f3f;
const double pi    = acos(-1.0);
const double inf   = 1e18;
const double eps   = 1e-8;
const LL    mod    = 1e9+7;
const ull    mx    = 133333331;

/*****************************************************/
inline void RI(int &x) {
      char c;
      while((c=getchar())<'0' || c>'9');
      x=c-'0';
      while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0';
 }
/*****************************************************/

int a[55];
int dp[2][MAX];

int main(){
    //freopen("in.txt","r",stdin);
    int t;
    cin>>t;
    while(t--){
        int n;
        cin>>n;
        for(int i=1;i<=n;i++) scanf("%d",&a[i]);
        //sort(a+1,a+n+1);
        mem(dp,-1);
        dp[0][0]=0;
        int cur=0;
        for(int i=1;i<=n;i++){
            cur^=1;
            for(int j=0;j<=500000;j++){
                dp[cur][j]=max(dp[cur][j],dp[cur^1][j]);
                if(j+a[i]<=500000&&dp[cur^1][j+a[i]]!=-1) dp[cur][j]=max(dp[cur][j],dp[cur^1][j+a[i]]+a[i]);
                if(j-a[i]>=0&&dp[cur^1][j-a[i]]!=-1) dp[cur][j]=max(dp[cur][j],dp[cur^1][j-a[i]]+a[i]);
                if(j-a[i]<0&&dp[cur^1][a[i]-j]!=-1) dp[cur][j]=max(dp[cur][j],dp[cur^1][a[i]-j]+a[i]);
            }
        }
        if(dp[cur][0]==0) printf("GG\n");
        else printf("%d\n",dp[cur][0]/2);
    }
    return 0;
}

你可能感兴趣的:(SCU 4512 Goozy的积木(dp))