The Number of Paths - HDU 1293 DP

来源:互联网 发布:软件系统维护方案 编辑:程序博客网 时间:2024/06/12 23:20

The Number of Paths

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 567    Accepted Submission(s): 264


Problem Description
Let f (n) be the number of paths with n steps starting from O (0, 0), with steps of the type (1, 0), or (-1, 0), or (0, 1), and never intersecting themselves. For instance, f (2) =7, as shown in Fig.1. Equivalently, letting E=(1,0),W=(-1,0),N=(0,1), we want the number of words A1A2...An, each Ai either E, W, or N, such that EW and WE never appear as factors.
 

Input
There are multiple cases in this problem and ended by the EOF. In each case, there is only one integer n means the number of steps(1<=n<=1000).
 

Output
For each test case, there is only one integer means the number of paths.
 

Sample Input
12
 

Sample Output
37
 


题意:每一步能向上、向左、向右走,且不能往回走(即向左走与向右走不能相邻),问n步有多少种前进路径


思路:首先定义方案数为a[n],考虑第k步可以从第k-1步转移来,但由于不能往回走,要减去上一步与这步同向的方案数,即a[k-1]-a[k-2]。

递推公式为:a[n]=3*a[n-1]-(a[n-1]-a[n-2]),整理得a[n]=2*a[n-1]+a[n-2]


Hint:爆long long,用大整数BigInteger


import java.util.Scanner;import java.math.*;public class HDU1293 {public static void main(String[] args) {Scanner in=new Scanner(System.in);BigInteger dp[]=new BigInteger[1050];dp[1]=new BigInteger("3");dp[2]=new BigInteger("7");int n;for(int i=3;i<=1000;i++)dp[i]=dp[i-2].add(dp[i-1].multiply(new BigInteger("2")));while(in.hasNext()){n=in.nextInt();System.out.println(dp[n]);}}}



0 0