FZU 2156(记忆化搜索)

Problem 2156 Climb Stairs

Accept: 153    Submit: 397
Time Limit: 1000 mSec    Memory Limit : 32768 KB

 Problem Description

Jason lives on the seventh floor. He can climb several stairs at a time, and he must reach one or more specific stairs before he arrives home because of obsessive-compulsive disorder.

Let us suppose:

1. Jason can climb X stairs or Y stairs at a time.

2. Jason wants to reach the N th stairs.

3. Jason must reach the Ath stairs and the Bth stairs before he reaches the Nth stairs.

Now, Jason wants to know how many ways he can reach the Nth stairs.

 Input

The input will consist of a series of test cases.

Each test case contains five integer: N, X, Y, A, B.

0<N<=10,000

0<X, Y<=10,000

0<A, B<=N

 Output

For each test case, output the answer mod 1,000,000,007.

 Sample Input

3 1 2 2 15 2 3 1 1

 Sample Output

10






题意:你可以每次走X或Y步,你要到达N台阶,在到达N台阶之前必训要达到A,B台阶,问有多少种方案


题解:开始写了一个大暴力,直接DFS,弱弱的交了上去果然TLE。于是就写了个记忆化,测了一下,诶过了样例诶,交一下AC了。。。。。,说一下思路吧。。使用一个三维数组,分别表示有没有访问A,B,和当前的走的步数,因为是从终点倒推到起点的,满足没有后效性的性质?原谅我DP很差。



#include<iostream>
#include<cstdio>
using namespace std;
int  N, X, Y, A, B;
#define mod int(1e9+7)
int dp[2][2][10005];

int dfs(int a,int b,int dep)
{
	if(dep==A)a=1;
	if(dep==B)b=1;
	if(dep>N)return 0;
	if(dep==N&&a&&b)
	{
		return dp[a][b][dep]=1;
	}
	if(dp[a][b][dep]!=-1)
		return dp[a][b][dep];
	dp[a][b][dep]=0;
	for(int i=0;i<2;i++)
	{
		if(i==0)dp[a][b][dep]=(dfs(a,b,dep+X)+dp[a][b][dep])%mod;
		else dp[a][b][dep]=(dfs(a,b,dep+Y)+dp[a][b][dep])%mod;
	}
	return dp[a][b][dep]%mod;
	
}
int main()
{
	while(~scanf("%d%d%d%d%d",&N, &X, &Y, &A, &B))
	{
		memset(dp,-1,sizeof(dp));
		printf("%d\n",dfs(0,0,0));
	}
	return 0;
}


你可能感兴趣的:(FZU 2156(记忆化搜索))