码迷,mamicode.com
首页 > 其他好文 > 详细

UVA - 12295 Optimal Symmetric Paths (递推)

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

标签:des   style   http   color   os   io   strong   for   

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 (递推)

标签:des   style   http   color   os   io   strong   for   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!