题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2563
这道题目我的第一想法是用BFS去做但是会超内存看完被人的题解之后,我恍然大悟,这道题目我为什么就是没有想到是递推呢?
我们可以这样来看这道题目,首先我们设f(n)为走第n步可以有的方案数,可以是由n-1步向上走,或者是向左向右走,
假设向上走的方案数为a(n),向左向右走的方案数为b(n),所以f(n)=a(n)+b(n);
如果是向上走的话,那么不管n-1步是怎么来的,都可以向上走;a(n)=f(n-1)=a(n-1)+b(n-1);如果是向左或向右走的话,如果n-1步是由n-2步向上走的来的话,没有关系即为2倍关系(可以向左走也可以向右走),但是如果是由向左或向右来的话,就不能往回走了(只能有一种选择了)。b(n)=2*a(n-1)+b(n-1);将a(n),b(n)代入得到f(n)=2*f(n-1)+f(n-2);
所以代码就简单了;
#include<cstdio>
#include<cstring>
#include<algorithm
>#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>using namespace std;
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int Max = 0x3f3f3f3f;
const int Min = 0xc0c0c0c0;
const int maxn = 123456;
#define mst(a) memset(a,0,sizeof(a))
#define w(i) while(i--)
#define forij(i,j,k,step)
for(int i=k;i<j;i+=step)
int t,n,m;
int a[maxn];
int main()
{
a[1]=3,a[2]=7;
for(int i=3;i<30;i++)
{
a[i]=2*a[i-1]+a[i-2];
}
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
printf("%d\n",a[n]);
}
}