HDU-1428-漫步校园 (bfs与dfs与记忆化搜索(dp))

版权声明:欢迎评论与转载,转载时请注明出处! https://blog.csdn.net/wjl_zyl_1314/article/details/84260252

原题链接:
http://acm.hdu.edu.cn/showproblem.php?pid=1428
LL最近沉迷于AC不能自拔,每天寝室、机房两点一线。由于长时间坐在电脑边,缺乏运动。他决定充分利用每次从寝室到机房的时间,在校园里散散步。整个HDU校园呈方形布局,可划分为n*n个小方格,代表各个区域。例如LL居住的18号宿舍位于校园的西北角,即方格(1,1)代表的地方,而机房所在的第三实验楼处于东南端的(n,n)。因有多条路线可以选择,LL希望每次的散步路线都不一样。另外,他考虑从A区域到B区域仅当存在一条从B到机房的路线比任何一条从A到机房的路线更近(否则可能永远都到不了机房了…)。现在他想知道的是,所有满足要求的路线一共有多少条。你能告诉他吗?
Input
每组测试数据的第一行为n(2=<n<=50),接下来的n行每行有n个数,代表经过每个区域所花的时间t(0<t<=50)(由于寝室与机房均在三楼,故起点与终点也得费时)。
Output
针对每组测试数据,输出总的路线数(小于2^63)。
Sample Input
3
1 2 3
1 2 3
1 2 3
3
1 1 1
1 1 1
1 1 1
Sample Output
1
6
题意:
中文题
题解:
对于这道题目
(我的TLE思路)
直接用dfs深搜搜索出每一条路线的耗时,然后利用map记录下每一个耗时出现的次数,最后输出耗时最短的次数。
(TLE的记忆化搜索思路)
知道了也要利用记忆化搜索后,我还是不忍心删掉这么多的dfs深搜,于是就用了dfs先找出了每一个点距离终点的距离,之后在用了一次dfs2深搜得到最短时间的耗时,结果还是TLE了。
(正确的记忆化搜索)
先利用bfs广搜得到每一个点到终点的最短距离,之后再利用dfs找出出现最短耗时的次数。(具体操作见代码)
附上AC代码:

#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
struct node{
    int x, y;
};//定义结构体,方便bfs时栈的需要
node S;
int n;
int dir[4][2]={1,0,0,1,-1,0,0,-1};//方向
long long st[55][55];//初始表
long long dp[55][55];//每一个点到终点的最短距离
long long cnt[55][55];//该点到终点走最短距离的线路

void bfs()
{
    queue<node> que;
    S.x = n, S.y = n;
    memset(dp, -1, sizeof(dp));
    dp[n][n] = st[n][n];
    que.push(S);
    while(!que.empty()){
        node u = que.front();
        que.pop();
        int x = u.x, y = u.y;
        for (int i = 0; i < 4; i++){
            int nx = x + dir[i][0];
            int ny = y + dir[i][1];
            if (nx<=0||nx>n||ny<=0||ny>n) continue;
            if (dp[nx][ny] == -1 || dp[x][y] +st[nx][ny] < dp[nx][ny])//找出最短距离
            {
                dp[nx][ny] = dp[x][y] + st[nx][ny];
                que.push((node){nx, ny});
            }
        }
    }
}
long long dfs(int x,int y)
{
    if (cnt[x][y]) return cnt[x][y];
    for (int i = 0; i < 4; i++){
        int nx = x + dir[i][0];
        int ny = y + dir[i][1];
        if (nx<=0||nx>n||ny<=0||ny>n) continue;
        if (dp[nx][ny] < dp[x][y])//只要是比该点到终点的最短距离小的(根据题意得到的,这点容易迷糊)
            cnt[x][y] += dfs(nx, ny);
    }
    return cnt[x][y];

}
int main()
{
    while(scanf("%d",&n)!=EOF)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                scanf("%lld",&st[i][j]);
            }
        }
        memset(dp,0,sizeof(dp));
        memset(cnt,0,sizeof(cnt));//重置
        bfs();
        cnt[n][n]=1;
        printf("%lld\n",dfs(1,1));
        //读者可以输出最终解果,更清楚的理解

        /*for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
                printf("%lld ",cnt[i][j]);
            puts("");
        }
        */
    }
    return 0;
}

欢迎评论!

猜你喜欢

转载自blog.csdn.net/wjl_zyl_1314/article/details/84260252