hdu 1428

记忆化搜索

View Code
#include<stdio.h>
#include<string.h>
#include<iostream>
#include<queue>
using namespace std;
struct nd
{
    int x,y;
};
const long long inf = 0xfffffff;

long long as[100][100],hash[100][100],dp[100][100];
long long dx[] = {1,-1,0,0};
long long dy[] = {0,0,1,-1};
long long n;

void BFS()
{
    long long i,xx,yy;
    struct nd s,t;
    s.x = n - 1; s.y = n - 1;
    queue<struct nd>que;
    que.push(s);
    hash[n-1][n-1] = as[n-1][n-1];
    while(!que.empty())
    {
        s = que.front(); que.pop();
        for(i = 0; i < 4; ++ i)
        {
            t.x = s.x + dx[i];
            t.y = s.y + dy[i];
            if(t.x<0||t.y<0||t.x==n||t.y==n)continue;
            long long dis = hash[s.x][s.y] + as[t.x][t.y];
            if(hash[t.x][t.y]>dis)
            {
                hash[t.x][t.y] = dis;
                que.push(t);
            }
        }
    }
}

long long DFS(long long x,long long y)
{
    long long min = inf;
    if(dp[x][y])return dp[x][y];
    
    for(long long i = 0; i < 4; ++ i)
    {
        long long xx = x + dx[i];
        long long yy = y + dy[i];
        if(xx<0||yy<0||xx==n||yy==n)continue;
        if(hash[xx][yy]<hash[x][y]) dp[x][y] += DFS(xx,yy);
    }
    return dp[x][y];
}

int main()
{
    long long i,j;
    while(scanf("%I64d",&n)==1)
    {
        for(i = 0; i < n; ++ i) for(j = 0; j < n; ++ j) scanf("%I64d",&as[i][j]);
        for(i = 0; i < n; ++ i) for(j = 0; j < n; ++ j) hash[i][j] = inf;
        BFS();
        memset(dp,0,sizeof(dp));
        dp[n-1][n-1] = 1;
        DFS(0,0);
        printf("%I64d\n",dp[0][0]);
    }return 0;
}

posted on 2012-04-27 16:01  aigoruan  阅读(169)  评论(0)    收藏  举报

导航