HDU - 1208Pascal's Travels (memory search related exercises 1)

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Topic links : https://cn.vjudge.net/contest/306123#problem/A
topic resolve map for n * n, go to the lower right corner from the top left corner, only to the right and down, meet figures in brackets a few steps away, except 0 (0 is a dead end and can not go), there are several ways to find?
The following figure illustrates well the path from the beginning to the end
Here Insert Picture Description
Note: The map is quite large, if a search for a likely time-out, you need to optimize -----> search through the data points remain, the next time this is the time to search directly with the data retained. Avoiding a repeat operation (jargon: search memory). Each point of the state preserved, illustrates this search and dp are inseparable.

For details of solving the problem
(1) When you call dfs, long long to write every time.
(2) This question can only be to the right and down, deal with this question also needs to coordinate accumulated.

Code:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
long long s;
int to[2][2]={1,0,0,1},n;
long long dp[50][50];//dp[i][j]:记录(i,j)到终点的路径
char a[50][50];
long long  dfs(int x,int y){
    int flag=0;
    long long s=0;//这个地方long long必须写,可能数据过大,题目中大致可能也是这个意思
    if(dp[x][y]!=-1)
        return dp[x][y];
    if(x==n-1&&y==n-1) //目标状态
        return 1; //路径加1
    if(a[x][y]=='0') {
        dp[x][y]=0; //对零的特判
        return 0;
    }
    for(int i=0; i<2; i++){
        int tx=(a[x][y]-'0')*to[i][0]+x; //下一点的坐标
        int ty=(a[x][y]-'0')*to[i][1]+y;
        if(tx>=0&&tx<n&&ty>=0&&ty<n){
            flag=1;
            s=s+dfs(tx,ty);
        }
    }//一个点搜到不能再搜了,才执行下面的if选择句
    if(flag==0)  //这一点向右和向左都无法走
    {
        dp[x][y]=0;
        return dp[x][y];
    }
    else
    {
        dp[x][y]=s;
        return dp[x][y];
    }
}
int main(){
    while(~scanf("%d",&n)) {
        if(n==-1)
            break;
        s=0;
        for(int i=0; i<n; i++) //输入地图
            scanf("%s",a[i]);
        memset(dp,-1,sizeof(dp));
        printf("%lld\n",dfs(0,0)); //dfs(0,0)为左上角
    }
    return 0;
}

And not because of a long night of fear
Here Insert Picture Description

Guess you like

Origin blog.csdn.net/lylzsx20172018/article/details/91900485