zoukankan      html  css  js  c++  java
  • E. Tetrahedron(数学推导)

     

    E. Tetrahedron

    分类: AC路漫漫
    time limit per test
     2 seconds
    memory limit per test
     256 megabytes
    input
     standard input
    output
     standard output

    You are given a tetrahedron. Let's mark its vertices with letters ABC and D correspondingly.

    An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place.

    You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertexD to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7).

    Input

    The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path.

    Output

    Print the only integer — the required number of ways modulo 1000000007 (109 + 7).

    Sample test(s)
    input
    2
    
    output
    3
    
    input
    4
    
    output
    21
    
    Note

    The required paths in the first sample are:

    • D - A - D
    • D - B - D
    • D - C - D

    解题说明:此题可以算是一道DP问题,从椎体的顶部D出发,指定走n步,要求最后回到D即可。假设走i步回到起点的走法数为f[i],那么可以得到

    f[i]=f[i-1]*2+f[i-2]*3

    这个公式的意思是说,在i-1步能走到起点的所有行走路线中,我们调整最后两步,让倒数第2步走到除当前点和起点外的另外两个点,最后一步再走到起点,所以选择是f[i-1]*2. 至于i-2步,依旧是考虑最后两个步骤,倒数第2步没有什么要求,选择有3种。有了这个公式,最后打表即可。

    1. #include<cstdio>  
    2. #include<iostream>  
    3. using namespace std;  
    4.   
    5. int main()  
    6. {  
    7.     unsigned int n;  
    8.     int i;  
    9.     long long f[10000001];   
    10.     f[1] = 0;   
    11.     f[2] = 3;   
    12.     f[3] = 6;   
    13.     for(i=4; i<10000001;i++)   
    14.     {   
    15.         f[i] = f[i-1] * 2 + f[i-2] * 3;   
    16.         f[i] %= 1000000007;   
    17.     }   
    18.     scanf("%d",  &n);  
    19.     cout<<f[n]<<endl;  
    20.     return 0;  
    21. }  
  • 相关阅读:
    设计模式(二):命令模式实例
    设计模式(一):简单工厂实例
    vue中使用base64进行加解密
    vue跨域问题解决(生产环境)
    彩色图像的直方图绘制及灰度图像均衡化
    MySql中添加用户,新建数据库,用户授权,删除用户,修改密码
    python办公入门2:开发准备工作
    python办公入门1:概述
    python菜鸟教程学习9:函数
    python菜鸟教程学习8:迭代器与生成器
  • 原文地址:https://www.cnblogs.com/get-an-AC-everyday/p/4307625.html
Copyright © 2011-2022 走看看