F - The Number of Paths

本文介绍了一种结合大数处理的递推算法,用于计算特定条件下从原点出发的不自交路径数量。通过逐步优化递推公式,解决了大数运算带来的挑战,并分享了代码实现细节。

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

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

原本就以为是一道简单的递推就能解决的问题,没想到牵连到了大数,结果又只好重写,而且本人的递推公式不适合大数,建议使用更简洁的公式a[i]=2*a[i-1]+a[i-2];而我自己使用的是c[i]=a[i]+b[i],

a[i]=a[i-1]+b[i-1];b[i]=2*a[i-1]+b[i-1];

#include<stdio.h>
#include<string.h>
#include<string>
#include<algorithm>
int a[1010][1000],b[1010][1000],c[1010][1000];
int main()
{
    memset(a,0,sizeof(a));memset(b,0,sizeof(b));memset(c,0,sizeof(c));
	a[1][1]=1,b[1][1]=2;a[1][0]=1,b[1][0]=1;c[1][0]=1,c[1][1]=3;
	for(int i=2;i<=1005;i++)
    {
        int j=1,x=0;
        while(j<=a[i-1][0]||j<=b[i-1][0]){
            a[i][j]=a[i-1][j]+b[i-1][j]+x;
            x=a[i][j]/10;a[i][j]%=10;j++;
        }
        a[i][j]=x;
        if(a[i][j]==0)j--;
        a[i][0]=j;
        j=1,x=0;
        while(j<=a[i-1][0]||j<=b[i-1][0]){
            b[i][j]=2*a[i-1][j]+b[i-1][j]+x;
            x=b[i][j]/10;b[i][j]%=10;j++;
        }
        b[i][j]=x;
        if(b[i][j]==0)j--;
        b[i][0]=j;
        j=1,x=0;
        while(j<=a[i][0]||j<=b[i][0])
        {
            c[i][j]=a[i][j]+b[i][j]+x;x=c[i][j]/10;c[i][j]%=10;j++;
        }
        c[i][j]=x;if(c[i][j]==0)j--;
        c[i][0]=j;
		//a[i]=a[i-1]+b[i-1];
		//b[i]=2*a[i-1]+b[i-1];
	}int n;
	while(scanf("%d",&n)!=EOF)
	{
	    for(int i=c[n][0];i>=1;i--)printf("%d",c[n][i]);
	    putchar('\n');

	}

	//printf("%d",strlen(a));
	return 0;
}

这个题目其实就是在于与大数结合,而递推其实不难。在本题中,觉得最大的收获就是在int类型中利用第一个元素来计数该数的位数。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值