首页 > 代码库 > UVA - 12295 Optimal Symmetric Paths (递推)
UVA - 12295 Optimal Symmetric Paths (递推)
Description
Optimal Symmetric Paths
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 a6 x 6 grid.
Your task is to find out, among all valid paths, how many of them have the minimal sum of digits?
Input
There will be at most 25 test cases. Each test case begins with an integer n ( 2n100). Each of the next n lines contains n non-zero digits (i.e. one of 1, 2, 3, ..., 9). These n2 integers are the digits in the grid. The input is terminated by a test case withn = 0, you should not process it.Output
For each test case, print the number of optimal symmetric paths, modulo 1,000,000,009.Sample Input
2 1 1 1 1 3 1 1 1 1 1 1 2 1 1 0
Sample Output
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; }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。