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
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <set>
#include <map>
#define ll long long
using namespace std;
const int MAXN = 50 + 10;
int C[MAXN][MAXN];
int dis[MAXN][MAXN];
long long dp[MAXN][MAXN];
int vis[MAXN][MAXN];
int Move[][2] = { {-1, 0}, {1, 0}, {0, -1}, {0, 1} };
int n;
struct Node
{
int x, y;
int step;
bool operator < (const Node& rhs) const
{
return step > rhs.step;
}
};
void bfs()
{
priority_queue<Node> Q;
memset(vis, 0, sizeof(vis));
Node pre, now;
pre.x = pre.y = n;
pre.step = C[n][n];
vis[n][n] = 1;
dis[n][n] = C[n][n];
Q.push(pre);
while(!Q.empty())
{
pre = Q.top();
Q.pop();
if(pre.x > 1 && !vis[pre.x-1][pre.y])
{
now.x = pre.x - 1;
now.y = pre.y;
now.step = pre.step + C[now.x][now.y];
dis[now.x][now.y] = now.step;
vis[now.x][now.y] = 1;
Q.push(now);
}
if(pre.x < n && !vis[pre.x+1][pre.y])
{
now.x = pre.x + 1;
now.y = pre.y;
now.step = pre.step + C[now.x][now.y];
dis[now.x][now.y] = now.step;
vis[now.x][now.y] = 1;
Q.push(now);
}
if(pre.y > 1 && !vis[pre.x][pre.y-1])
{
now.x = pre.x;
now.y = pre.y - 1;
now.step = pre.step + C[now.x][now.y];
dis[now.x][now.y] = now.step;
vis[now.x][now.y] = 1;
Q.push(now);
}
if(pre.y < n && !vis[pre.x][pre.y+1])
{
now.x = pre.x;
now.y = pre.y + 1;
now.step = pre.step + C[now.x][now.y];
dis[now.x][now.y] = now.step;
vis[now.x][now.y] = 1;
Q.push(now);
}
}
}
long long solve(int x, int y)
{
if(dp[x][y] != -1)
return dp[x][y];
dp[x][y] = 0;
if(x > 1 && dis[x][y] > dis[x-1][y]) dp[x][y] += solve(x-1, y);
if(x < n && dis[x][y] > dis[x+1][y]) dp[x][y] += solve(x+1, y);
if(y > 1 && dis[x][y] > dis[x][y-1]) dp[x][y] += solve(x, y-1);
if(y < n && dis[x][y] > dis[x][y+1]) dp[x][y] += solve(x, y+1);
return dp[x][y];
}
int main()
{
while(scanf("%d", &n)!=EOF)
{
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
scanf("%d", &C[i][j]);
}
bfs();
//for(int i=1;i<=n;i++)
//{
// for(int j=1;j<=n;j++)
// cout << dis[i][j] << ' ';
//cout << endl;
//}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
dp[i][j] = -1;
}
dp[n][n] = 1;
printf("%I64d\n", solve(1, 1));
}
return 0;
}
原文地址:http://blog.csdn.net/moguxiaozhe/article/details/45224671