luogu 1437 敲砖块(DP)

这道题的DP的状态设计的很有想法啊。

假如我们一行一行来选择的话,状态将会极其复杂。

如果一列一列来看的话,比如你想选aij,那么第i列的前j个都要选,并且第i+1列的前j-1个都要选。

于是状态就很好设计了,定义dp[n][i][j]表示还剩下n个要选的砖块,当前选择第i列的前j个所能达到的最大分值。

那么dp[n][i][j]=max(dp[n-j][i+1][k]+sum[i][j])(j-1<=k<=n-i).

记忆化搜索一下就OK了。

 

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-7
# define MOD 1024523
# define INF 1000000000
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<1,l,mid
# define rch p<<1|1,mid+1,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
void Out(int a) {
    if(a<0) {putchar('-'); a=-a;}
    if(a>=10) Out(a/10);
    putchar(a%10+'0');
}
const int N=55;
//Code begin...

int a[N][N], sum[N][N], dp[N*N][N][N], n;

int dfs(int x, int col, int row){
    if (x<0||(col>n&&x)) return -INF;
    if (~dp[x][col][row]) return dp[x][col][row];
    if (x==0) return row==0?0:-INF;
    int res=-INF;
    FOR(i,max(0,row-1),min(x,n-col)) res=max(res,dfs(x-row,col+1,i)+sum[col][row]);
    return dp[x][col][row]=res;
}
int main ()
{
    int m, ans=0;
    scanf("%d%d",&n,&m); mem(dp,-1);
    FOR(i,1,n) FOR(j,1,n-i+1) scanf("%d",&a[i][j]), sum[j][i]=sum[j][i-1]+a[i][j];
    FOR(i,0,n) ans=max(ans,dfs(m,1,i));
    printf("%d\n",ans);
    return 0;
}
View Code

 

posted @ 2017-05-11 23:46  free-loop  阅读(159)  评论(0编辑  收藏  举报