hdu 2563 统计问题
在一无限大的二维平面中,我们做如下假设:
1、 每次只能移动一格;
2、 不能向后走(假设你的目的地是“向上”,那么你可以向左走,可以向右走,也可以向上走,但是不可以向下走);
3、 走过的格子立即塌陷无法再走第二次;
求走n步不同的方案数(2种走法只要有一步不一样,即被认为是不同的方案)。
Input
首先给出一个正整数C,表示有C组测试数据
接下来的C行,每行包含一个整数n (n<=20),表示要走n步。
Output
请编程输出走n步的不同方案总数;
每组的输出占一行。
Sample Inpu
t2
1
2
Sample Output
3
7
思路:
1.递归实现:
对于第 n 步,只与 n-1 和 n-2 步有关,
a[n] 表示第 n 步的方案
由于 第 n 步 由 第 n-1 步而来,所以只考虑 n-1 步左右走,有 2a[n-1] 种方案,但是 a[n-1] 中存在向上走的方案,而 n-1 步中的向上走的方案全部来自 n-2 中的方案。
故 a[n] = 2a[n-1] + a[n-2]
2.借助动态规划的思想:
将没步的向上和向左右分开来考虑,
用 a[n][0] 表示第 n 步的左右方案
用 a[n][1] 表示第 n 步的向上方案
则 总方案 = a[n][1] + a[n][0]
而:
a[n][0] = a[n-1][1]*2 + a[n-1][0]
a[n][1] = a[n-1][1] + a[n-1][0]
代码:
#include <iostream>
#include <algorithm>
#include<string.h>
#include<math.h>
#include<numeric>
using namespace std;
int main()
{
int C;
scanf("%d",&C);
while (C--)
{
int n;
scanf("%d",&n);
int a[21][2];
memset(a,0,sizeof(a));
a[0][1] = 1;
int i;
for (i=1;i<=n;i++)
{
a[i][0] = a[i-1][0] + 2*a[i-1][1];
a[i][1] = a[i-1][1] + a[i-1][0];
}
int res = 0;
res = a[n][0] + a[n][1];
printf("%d\n",res);
}
}