您的位置:首页 > 大数据 > 人工智能

URAL 1017 Staircases 楼梯

2016-03-07 17:11 405 查看

递推:

设dp[tot][x]表示一共用tot个block,最后一个台阶block的个数为x个。

所以dp[tot][x]=dp[tot-1][x-1]+dp[tot-x][x-1];

可以这样理解:
计算用tot个block&&最后一个台阶block数为x的种数:
因为最后一个台阶block数已经知道是x了,
所以只用关心倒数第二个台阶。
ans=倒数第二个台阶放[1,x-2]个block的种数+倒数第二个台阶放x-1个block的种数。

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int INF =0x3f3f3f3f;
const int maxn= 500 ;
ll dp[maxn+4][maxn+4];

void work()
{

// memset(dp[0],0,sizeof dp[0]);
for(int tot=1;tot<=maxn;tot++)
{
dp[tot][0]=0;
for(int x=1;x<=tot;x++)
{
if(tot==1&&x==1) {dp[tot][x]=1;continue;}
dp[tot][x]=dp[tot-1][x-1]+dp[tot-x][x-1];
}
}
/*
摘自http://www.cnblogs.com/xiongqiangcs/archive/2013/05/09/3068379.html
这样写更简洁
for(int i = 2; i <= N; i ++ ){
for(int j = 1; j <= i; j ++){
dp[i][j] = dp[i-1][j-1] + dp[i-j][j-1];
}
}
*/
}
int main()
{
work();
int x;
while(~scanf("%d",&x))
{
ll ans=0;
for(int i=1;i<=x;i++)
{
ans+=dp[x][i];
}
ans--;
printf("%lld\n",ans);
}

return 0;
}


记忆化搜索

 
因为层数不确定,用记忆化搜索解决也比较合适。

#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
using namespace std;
typedef long long ll;
const int INF =0x3f3f3f3f;
const int maxn= 500   ;
int n;
ll dp[maxn+4][maxn+4];
ll DP(int x,int least)
{
if(~dp[x][least])  return dp[x][least];
if(!x)  return dp[x][least]=1;

ll ans=0;
for(int i=least;i<=x;i++)
{
ans+=DP(x-i,i+1);
}
return dp[x][least]=ans;
}
int main()
{
memset(dp,-1,sizeof dp);
while(~scanf("%d",&n))
{
printf("%lld\n",DP(n,1)-1);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: