码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1428 漫步校园 (BFS + 记忆化搜索)

时间:2015-04-26 09:17:07      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:hdu   记忆化搜索   


漫步校园

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 3360    Accepted Submission(s): 1009

Problem Description
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
 

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1428


题目分析:和hdu 1142类似,不过这题给的是点权,还是要求最短路,用BFS搜一下,每个点到右下角的最短路,然后记忆化搜索次数


#include <cstdio>
#include <cstring>
#include <queue>
#define ll long long 
using namespace std;
int const MAX = 55;
int dis[MAX][MAX], map[MAX][MAX];
ll dp[MAX][MAX];
int n;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, -1, 0, 1};

struct NODE
{
    int x, y;
};

void BFS()
{
    queue <NODE> q;
    NODE st;
    st.x = n;
    st.y = n;
    dis[n][n] = map[n][n];
    q.push(st);
    while(!q.empty())
    {
        NODE cur = q.front(), t;
        q.pop();
        for(int i = 0; i < 4; i++)
        {
            t.x = cur.x + dx[i];
            t.y = cur.y + dy[i];
            if(t.x < 1 || t.y < 1 || t.x > n || t.y > n)
                continue;
            if(dis[t.x][t.y] > dis[cur.x][cur.y] + map[t.x][t.y] || dis[t.x][t.y] == -1)
            {
                dis[t.x][t.y] = dis[cur.x][cur.y] + map[t.x][t.y];
                q.push(t);
            }
        }
    }
}

ll DFS(int x, int y)
{
    if(dp[x][y])
        return dp[x][y];
    if(x == n && y == n)
        return 1;
    ll tmp = 0;
    for(int i = 0; i < 4; i++)
    {
        int xx = x + dx[i];
        int yy = y + dy[i];
        if(xx > n || yy > n || xx < 1 || yy < 1 || dis[xx][yy] >= dis[x][y])
            continue;
        tmp += DFS(xx, yy);
    }
    return dp[x][y] = tmp;
}

int main()
{
    while(scanf("%d", &n) != EOF)
    {
        memset(dis, -1, sizeof(dis));
        memset(dp, 0, sizeof(dp));
        for(int i = 1; i <= n; i++)
            for(int j = 1; j <= n; j++)
                scanf("%d", &map[i][j]);
        BFS();
        printf("%I64d\n", DFS(1, 1));
    }
}


HDU 1428 漫步校园 (BFS + 记忆化搜索)

标签:hdu   记忆化搜索   

原文地址:http://blog.csdn.net/tc_to_top/article/details/45285669

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!