uva 12295 Optimal Symmetric Paths__DP

来源:互联网 发布:银行数据采集器 编辑:程序博客网 时间:2024/05/28 23:10

Optimal Symmetric Paths 

You have a grid of n rows and n columns. Each of the unit squares contains a non-zero digit. Youwalk from the top-left square to the bottom-right square. Each step, you can move left, right, up ordown to the adjacent square (you cannot move diagonally), but you cannot visit a square more thanonce. There is another interesting rule: your path must be symmetric about the line connecting thebottom-left square and top-right square. Below is a symmetric path in a6x 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 thenext n lines contains n non-zero digits (i.e. one of 1, 2, 3, ..., 9). These n2 integers are the digits in thegrid. 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 

21 11 131 1 11 1 12 1 10

Sample Output 

23
#include<stdio.h>#define N 101#define MAX 1000000009/*对路径长度和数量同时DP,策略是对角线向起终点两端扩展;*/int dp[N][N],n,pat[N][N];int solve(){    int i,j,k,f;    for(i=0;i<n;++i)            pat[i][i]=1;    for(k=1;k<n;++k)        for(i=k,j=0;i<n;++i,++j)            {                f=dp[i][j+1]-dp[i-1][j];                dp[i][j]+=dp[j][i];                if(f>0)                {                    pat[i][j]=pat[i-1][j];                    dp[i][j]+=dp[i-1][j];                }                else if(f<0)                {                    pat[i][j]=pat[i][j+1];                    dp[i][j]+=dp[i][j+1];                }                else                {                    pat[i][j]=(pat[i][j+1]+pat[i-1][j])%MAX;                    dp[i][j]+=dp[i][j+1];                }            }    return pat[n-1][0];}int main(){    while(scanf("%d",&n)==1&&n)    {        int i,j;        for(i=n-1;i>=0;--i)            for(j=0;j<n;++j)                scanf("%d",&dp[i][j]);        printf("%d\n",solve());    }    return 0;}