【HDU 1208】Pascal's Travels(动态规划DP)

##Pascal’s Travels
Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u
##Description
An n x n game board is populated with integers, one nonnegative integer per square. The goal is to travel along any legitimate path from the upper left corner to the lower right corner of the board. The integer in any one square dictates how large a step away from that location must be. If the step size would advance travel off the game board, then a step in that particular direction is forbidden. All steps must be either to the right or toward the bottom. Note that a 0 is a dead end which prevents any further progress.

Consider the 4 x 4 board shown in Figure 1, where the solid circle identifies the start position and the dashed circle identifies the target. Figure 2 shows the three paths from the start to the target, with the irrelevant numbers in each removed.
这里写图片描述

##Input
The input contains data for one to thirty boards, followed by a final line containing only the integer -1. The data for a board starts with a line containing a single positive integer n, 4 <= n <= 34, which is the number of rows in this board. This is followed by n rows of data. Each row contains n single digits, 0-9, with no spaces between them.

##Output
The output consists of one line for each board, containing a single integer, which is the number of paths from the upper left corner to the lower right corner. There will be fewer than 2^63 paths for any board.

##Sample Input
4
2331
1213
1231
3110
4
3332
1213
1232
2120
5
11101
01111
11111
11101
11101
-1

##Sample Output
3
0
7
Hint
Hint Brute force methods examining every path will likely exceed the allotted time limit.
64-bit integer values are available as “__int64” values using the Visual C/C++ or “long long” values
using GNU C/C++ or “int64” values using Free Pascal compilers.

#####PS:所谓动态规划,就是每一个阶段你要做出一个决策。从开始的决策到结束的决策的集合叫一个策略,而各个阶段的决策的多样性直接导致了策略的多种多样。而我们一般求得不是最优策略就是最大话费策略。每一个阶段的决策在这种有目的性的作用下都与上一个阶段的决策相关。我们用记录这个阶段的一个东西(通常用动态数组)来记录这个状态的 符合我们需要的策略 的决策。

这题的动态过程就是将在(i,j)点的方法数存入dp[i][j],我们从开始遍历到结束(在不越界且当前还有策略步入下个状态的情况下)。

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"

using namespace std;

const int maxn = 35;

char str[maxn];
long long map[maxn][maxn];
long long dp[maxn][maxn];
int n;

int main(){
	while( ~scanf("%d",&n) ){
		if(n==-1) break;
		for( int i=0 ; i<n ; i++){
			scanf("%s",str);
			for( int j=0 ; j<n ; j++ ){
				map[i][j] = str[j]-'0';
			}
		}
		memset(dp,0,sizeof(dp));


		dp[0][0] = 1;
		for( int i=0 ; i<n ; i++ ){
			for( int j=0 ; j<n ; j++ ){
				if(!map[i][j]) continue;
				if(i+map[i][j]<n){
					dp[i+map[i][j]][j] += dp[i][j];
				}
				if(j+map[i][j]<n){
					dp[i][j+map[i][j]] += dp[i][j];
				}
			}
		}
		printf("%lld\n",dp[n-1][n-1]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/thesprit/article/details/52046568