HDU 1293 The Number of Paths

本文介绍了一个路径计数问题,通过动态规划的方法解决了一个从起点出发,仅允许向上、向左或向右移动,且不能重复经过同一位置的问题。文中给出了递推公式并提供了一段Java代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1293



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
1 2
 

Sample Output
3 7
 

Author
SmallBeer (CML)


题目大意:给出已知线段的段数(即前进的步数),线段的前进方向不可以向下,求有多少种走方。

要求第N步的走方数:

走第N步就必须走完N-1步,而在N-1步里面有方向向上,向左,向右三种情况。向左和向右的下一步只有俩种走法(即向上、同向),向上的下一步有三种走法。

所以需要统计在N-1步里面有多少向上的。

在N-2的步法里面每一种都只能产生一种向上的步法,即在N-1里面有向上的步法q[n-2]种。

递推式:q[n]=2*q[n-1]+q[n-2];


AC代码:

import java.math.BigInteger;
import java.util.Scanner;


public class Main {
 public static void main(String[] args) 
{
  
  int n;
  Scanner cin =new Scanner(System.in);
  while(cin.hasNext())
  {
   BigInteger ans=BigInteger.valueOf(3);
   BigInteger count=BigInteger.valueOf(1);
   BigInteger sum;
   n=cin.nextInt();
   for(int i=2;i<=n;i++)
   {
   	 sum=ans;
     ans=ans.multiply(BigInteger.valueOf(2));
     ans=ans.add(count);
     count=sum;
   }
   System.out.println(ans);
  }
 }

}

路途中。。。。。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值