Problem P

Problem Description
在一无限大的二维平面中,我们做如下假设:
1、  每次只能移动一格;
2、  不能向后走(假设你的目的地是“向上”,那么你可以向左走,可以向右走,也可以向上走,但是不可以向下走);
3、  走过的格子立即塌陷无法再走第二次;

求走n步不同的方案数(2种走法只要有一步不一样,即被认为是不同的方案)。

Input
首先给出一个正整数C,表示有C组测试数据
接下来的C行,每行包含一个整数n (n<=20),表示要走n步。

Output
请编程输出走n步的不同方案总数;
每组的输出占一行。

Sample Input
2
1
2

Sample Output
3
7
题意:略;
解题思路:刚开始是想的,找规律但是。。。。。。(前几个画了几遍太烦了。。。)最后还是深搜打表,但是深搜会超时,所以就直接打表了;
感悟:在人家考试的教室里撸代码,这是怎么样的境界啊;
代码:
#include
#include
#include
using namespace std;
int main()
{
    int ans[21]={0,3,7,17,41,99,239,577,1393,3363,8119,19601,47321,114243,275807,665857,1607521,3880899,9369319,22619537,54608393};
    int c,a;
    scanf("%d",&c);
    while(c--)
    {
        scanf("%d",&a);
        printf("%d ",ans[a]);
    }
}
深搜递归打表
#include
#include
#include
#define maxn 500
using namespace std;
bool visit[maxn][maxn];
int dir[3][2]= {{-1,0},{1,0},{0,1}}; //这里假设只能向下走,和左右
int t,n,a,ans[25],cur;
void dfs(int x,int y,int n)
{
    if(n==0)
    {
        cur++;
        return ;//一种走法
    }
    for(int i=0;i<3;i++)
    {
        int sx=x+dir[i][0];
        int sy=y+dir[i][1];
        if(visit[sx][sy])//走过了
            continue;
        visit[sx][sy]=true;
        dfs(sx,sy,n-1);
        visit[sx][sy]=false;
    }
    return ;
}
int main()
{
    freopen("in.txt","r",stdin);
    ans[0]=0;
    for(int i=1;i<=20;i++)
    {
        memset(visit,false ,sizeof visit);
        t=cur=0;
        visit[21][0]=true;
        dfs(21,0,i);
        ans[i]=cur;
    }
    int C;
    for(int i=0;i<=20;i++)
        cout<<ans[i]<<" ";
    cout<<endl;
    scanf("%d",&C);
    while(C--)
    {
        scanf("%d",&a);
        printf("%d ",ans[a]);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/wuwangchuxin0924/p/5781571.html