题目链接:hdoj 1428 漫步校园
漫步校园
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 3754 Accepted Submission(s): 1140
Problem Description
LL最近沉迷于AC不能自拔,每天寝室、机房两点一线。由于长时间坐在电脑边,缺乏运动。他决定充分利用每次从寝室到机房的时间,在校园里散散步。整个HDU校园呈方形布局,可划分为n*n个小方格,代表各个区域。例如LL居住的18号宿舍位于校园的西北角,即方格(1,1)代表的地方,而机房所在的第三实验楼处于东南端的(n,n)。因有多条路线可以选择,LL希望每次的散步路线都不一样。另外,他考虑从A区域到B区域仅当存在一条从B到机房的路线比任何一条从A到机房的路线更近(否则可能永远都到不了机房了…)。现在他想知道的是,所有满足要求的路线一共有多少条。你能告诉他吗?
思路:dp[i][j]为到达(i, j)位置的结果。预处理一次最短路,然后套个记忆化。
AC代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
#include <stack>
#define PI acos(-1.0)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define fi first
#define se second
#define ll o<<1
#define rr o<<1|1
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int MAXN = 2*1e5 + 10;
const int pN = 1e6;// <= 10^7
const int INF = 0x3f3f3f3f;
const int MOD = 1e9 + 7;
void add(LL &x, LL y) { x += y; x %= MOD; }
LL dp[60][60];
int dist[60][60], Map[60][60];
int n;
struct Node {
int x, y, d;
};
int Move[4][2] = {0,1, 0,-1, 1,0, -1,0};
bool judge(int x, int y) {
return x >= 1 && x <= n && y >= 1 && y <= n;
}
void BFS() {
Node now, next; queue<Node> Q;
now.x = n; now.y = n; now.d = Map[n][n];
dist[n][n] = Map[n][n]; Q.push(now);
while(!Q.empty()) {
now = Q.front(); Q.pop();
for(int k = 0; k < 4; k++ ){
next.x = now.x + Move[k][0];
next.y = now.y + Move[k][1];
if(judge(next.x, next.y)) {
next.d = now.d + Map[next.x][next.y];
if(dist[next.x][next.y] > next.d) {
dist[next.x][next.y] = next.d;
Q.push(next);
}
}
}
}
}
LL DFS(int x, int y) {
if(dp[x][y] != -1) return dp[x][y];
if(x == n && y == n) return 1;
LL ans = 0; int nx, ny;
for(int k = 0; k < 4; k++) {
nx = x + Move[k][0];
ny = y + Move[k][1];
if(judge(nx, ny)) {
if(dist[nx][ny] < dist[x][y]) {
ans += DFS(nx, ny);
}
}
}
dp[x][y] = ans;
return ans;
}
int main() {
while(scanf("%d", &n) != EOF) {
for(int i = 1; i <= n; i++) {
for(int j = 1; j <= n; j++) {
scanf("%d", &Map[i][j]);
dist[i][j] = INF;
}
}
BFS(); CLR(dp, -1);
printf("%lld\n", DFS(1, 1));
}
return 0;
}