Description
Optimal Symmetric Paths |
You have a grid of n rows and n columns. Each of the unit squares contains a non-zero digit. You walk from the top-left square to the bottom-right square. Each step, you can move left, right, up or down to the adjacent square (you cannot move diagonally), but you cannot visit a square more than once. There is another interesting rule: your path must be symmetric about the line connecting the bottom-left square and top-right square. Below is a symmetric path in a 6 x 6 grid.
Your task is to find out, among all valid paths, how many of them have the minimal sum of digits?
2 1 1 1 1 3 1 1 1 1 1 1 2 1 1 0
2 3 题意:求从左上角到右下角的最短路径数,且要求沿斜线对称 思路:既然要求对称,所以我们将对称的权值叠加,那么就是求到对角线的最短路径了,通过递推解决#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn = 111; const int mod = 1000000009; int n, num[maxn][maxn]; int dp[maxn][maxn]; void solve() { memset(dp, 0, sizeof(dp)); for (int i = 1; i <= n; i++) dp[i][n-i+1] = 1; for (int k = n; k >= 2; k--) for (int i = k-1; i >= 1; i--) { int j = k - i; if (num[i+1][j] < num[i][j+1]) { num[i][j] += num[i+1][j]; dp[i][j] = dp[i+1][j]; } if (num[i+1][j] > num[i][j+1]) { num[i][j] += num[i][j+1]; dp[i][j] = dp[i][j+1]; } if (num[i+1][j] == num[i][j+1]) { num[i][j] += num[i+1][j]; dp[i][j] = (dp[i+1][j] + dp[i][j+1]) % mod; } } } int main() { while (scanf("%d", &n) != EOF && n) { for (int i = 1; i <= n; i++) for (int j = 1; j <= n; j++) scanf("%d", &num[i][j]); for (int i = 1; i < n; i++) for (int j = 1; i+j <= n; j++) num[i][j] += num[n-j+1][n-i+1]; solve(); printf("%d\n", dp[1][1]%mod); } return 0; }
UVA - 12295 Optimal Symmetric Paths (递推),布布扣,bubuko.com
UVA - 12295 Optimal Symmetric Paths (递推)
原文:http://blog.csdn.net/u011345136/article/details/38611871