zoukankan      html  css  js  c++  java
  • Tiling

    openjudge上的一道题,在这里将高精度和递归递推巧妙的结合在了一起

    Tiling

    In how many ways can you tile a 2 × n rectangle by 2 × 1 or 2 × 2 tiles?

    Here is a sample tiling of a 2 × 17 rectangle.

    Input

    Input is a sequence of lines, each line containing an integer number 0 ≤ n ≤ 250.

    Output

    For each line of input, output one integer number in a separate line giving the number of possible tilings of a 2 × n rectangle.

    Sample Input

    2

    8

    12

    100

    200

    Sample Output

    3

    171

    2731

    845100400152152934331135470251

    1071292029505993517027974728227441735014801995855195223534251

    本题的递推公式很容易得到a[i]+=a[i-1]+a[i-2]*2

    那么重点便集中在了如何用高精度来计算数列200多位的数据上?不用指望longlong,它也救不了你。

    其实高精度的宗旨就是用数组记录,用进位来更改数据,所以既然我们在计算a[i]时还需要计算a[i-2],那么用一维数组是一定解决不了问题的,所以我们需要用上二位数组

    到了这里,这道题的核心内容就讲完了(PS:1.由于代码原因,需要逆向输出,这只是个人习惯,正向输出也没问题,只不过读取长度时还需多费心思   2.注意代码的另一个巧妙之处,读取int类型数组长度,这个很常用)

    附上本题代码

     1 #include<cstring>
     2 #include<cstdio>
     3 #include<cmath>
     4 using namespace std;
     5 int len[255],a[255][305],n,k;
     6 int main()
     7 {
     8     memset(a,0,sizeof(a));
     9     memset(len,1,sizeof(len));
    10     a[0][1]=1;
    11     a[1][1]=1;
    12     for(int i=2; i<=250; i++)
    13     {
    14         for(int j=1; j<=300; j++)
    15         {
    16             a[i][j]+=a[i-1][j]+a[i-2][j]*2;
    17             if(a[i][j]>=10)
    18                 a[i][j+1]=a[i][j]/10,a[i][j]%=10;
    19         }
    20         for(k=300; k>=1; k--)
    21             if(a[i][k]>0)
    22                 break;
    23         len[i]=k;
    24     }
    25     while(scanf("%d",&n)!=EOF)
    26     {
    27         if(n>1)
    28         {
    29             for(int i=len[n]; i>=1; i--)
    30                 printf("%d",a[n][i]);
    31             printf("
    ");
    32         }
    33         else
    34             printf("1
    ");
    35     }
    36     return 0;
    37 }
  • 相关阅读:
    在类中声明常量
    PHPStudy配置虚拟主机配置域名步骤
    PHPStudy配置虚拟主机步骤
    2019年7月22日星期一,简单的总结一下
    简单的面向对象
    session和cookie
    Jquery 事件绑定 bind 与on 的区别
    php try catch用法
    include,include_once,require,require_once的区别
    require与 include区别
  • 原文地址:https://www.cnblogs.com/yufenglin/p/10093908.html
Copyright © 2011-2022 走看看