hdu 1428 漫步校园

http://acm.hdu.edu.cn/showproblem.php?pid=1428


这个题一开始没看懂意思。其实这个题很好,综合搜索题。
其实和北大上面的   滑雪  题差不多的。不过这个题要先用广搜把每个点到机房(终点(n,n)的距离),然后再用深搜起点(1,1)到终点有几条路,不过有个条件就是每次走一步都要离终点越来越近。
所以我用了一个dis数组存每个点到终点最短距离。hash数组记忆每个点到终点有几条路径。

AC代码:
#include<iostream>
#include<cstdio>
#include<queue>
#include<cstring>

using namespace std;

#define MAX 9999999

struct Node
{
    int x,y;
}p;

int n;
int map[55][55];        //每个点经过所需时间
int dis[55][55];        //每个点到机房的时间
__int64 hash[55][55];   //记忆化记录每个点到终点有几条路径
int dir[4][2] = {{0,1},{1,0},{0,-1},{-1,0}};

void Bfs()     //广搜找每一点到终点的最短距离
{
    Node now,next;
    queue<Node> q;
    int m;           //临时步骤
    q.push(p);
    dis[n][n] = map[n][n];   //记录终点的距离
    while(!q.empty())
    {
        now = q.front();
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            next.x = now.x+dir[i][0];
            next.y = now.y+dir[i][1];
            if(next.x>=1 && next.y>=1 && next.x<=n && next.y<=n)
            {
                m = dis[now.x][now.y] + map[next.x][next.y];
                if(dis[next.x][next.y] > m)   //更新更最短路径并入队..
                {
                    dis[next.x][next.y] = m;
                    q.push(next);
                }
            }
        }
    }
    return ;
}

__int64 Dfs(int x, int y)     //记忆化深搜hash存每个点到机房有几条路径
{
    int i;
    int nx,ny;
    if(hash[x][y]>0)          //记忆化搜索,如果搜过,则直接返回结果
    {
        return hash[x][y];
    }
    if(x == n && y == n)      //在终点的路径只有1条
    {
        return 1;
    }
    for(i = 0; i < 4; i++)
    {
        nx = x+dir[i][0];
        ny = y+dir[i][1];
        if(nx>=1 && nx<=n && ny>=1 && ny<=n)
        {
            if(dis[nx][ny]<dis[x][y])   //只有当路径越来越短才能走
            {
                hash[x][y]+=Dfs(nx,ny);
            }
        }
    }
    return hash[x][y];
}

int main()
{
    int i,j;
    __int64 sum;
    while(scanf("%d",&n)!=EOF)
    {
        memset(map,0,sizeof(map));
        memset(dis,MAX,sizeof(dis));
        memset(hash,0,sizeof(hash));  //初始化每个点到机房没有路径
        for(i = 1; i <= n; i++)
        {
            for(j = 1; j <= n; j++)
            {
                scanf("%d",&map[i][j]);
            }
        }
        p.x = p.y = n;
        Bfs();
        sum = Dfs(1,1);
        /*
        for(i = 1; i <= n; i++)
        {
            for(j = 1; j <= n; j++)
            {
                printf("%3d ",dis[i][j]);
            }
            printf("\n");
        }*/
        printf("%I64d\n",sum);
    }

    return 0;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值