UVA - 12295 Optimal Symmetric Paths (递推)

Description

Download as PDF


  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.

\epsfbox{p12295.eps}

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 ( 2$ \le$n$ \le$100). 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 with n = 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;
}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值