首页 > 其他 > 详细

UVA - 12295 Optimal Symmetric Paths (递推)

时间:2014-08-16 12:36:50      阅读:397      评论:0      收藏:0      [点我收藏+]

Description

bubuko.com,布布扣


  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.

bubuko.com,布布扣

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 ( 2bubuko.com,布布扣nbubuko.com,布布扣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;
}



UVA - 12295 Optimal Symmetric Paths (递推),布布扣,bubuko.com

UVA - 12295 Optimal Symmetric Paths (递推)

原文:http://blog.csdn.net/u011345136/article/details/38611871

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!