hdoj.1293 The Number of Paths【大数+排列组合】 2015/08/07

本文介绍了一个路径计数问题,即从原点出发,在特定步数内不重复经过任何位置的所有可能路径数量。通过递推公式 f(n) = 2 * f(n-1) + f(n-2),使用 C++ 实现了计算过程。

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

The Number of Paths

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


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)
 

Source

注:f(n) = 2*f(n-1)+f(n-2)
#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;

int p[1010][500];

int main(){
    //int p[1010][500];
    memset(p,0,sizeof(p));
    p[0][1] = 1;
    p[1][1] = 3;
    p[0][0] = p[1][0] = 1;
    for( int i = 2 ; i <= 1000 ; ++i ){
        for( int j = 1 ; j <= p[i-1][0] ; ++j )
            p[i][j] = p[i-1][j] * 2 + p[i-2][j];
        for( int j = 1 ; j <= p[i-1][0] ; ++j ){
            if( p[i][j] > 9 ){
                p[i][j+1] += p[i][j] / 10;
                p[i][j] %= 10;
            }
        }
        p[i][0] = p[i][p[i-1][0]+1] ? p[i-1][0] + 1 : p[i-1][0] ;
    }
    int n;
    while(cin>>n){
        for( int i = p[n][0] ; i > 0 ; --i )
            printf("%d",p[n][i]);
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值