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. }  
  • 相关阅读:
    Silverlight:拖动滚动条控制媒体播放
    黑马程序员第一阶段3.面向对象第5天
    黑马程序员第一阶段2.java编程基础第4天
    黑马程序员第一阶段2.java编程基础第2天
    黑马程序员第一阶段2.java编程基础第3天
    黑马程序员第一阶段3.面向对象第6天
    黑马程序员第一阶段3.面向对象第8天
    黑马程序员第一阶段3.面向对象第7天
    黑马程序员第一阶段1.Java开发前奏第1天
    hdu 1133
  • 原文地址:https://www.cnblogs.com/get-an-AC-everyday/p/4307625.html
Copyright © 2011-2022 走看看