ACM题解——训练赛1_A

ACM题解——训练赛1_A题(应该算一道数学题)

题目描述

A - Tetrahedron

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 vertex D 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).

 

Examples

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

题意

题目给定一个四面体,从D点出发,通过n步回到D,求路径条数。

换个角度来看就是已知ABCD点,任两条互通,求从D近n步回到D的路径条数。结果对10^9+7取余输出。

 

题解

解法一:

可以看出本题是一个递归题,先考虑从D点出发走n步有多少种走法,因为每一步都有三个点可选择,所以是3^n次,但是要求结尾这个点必须是D,那么上一个点就不应该是D点,且最后一次没得选必须回到D点,因此是3^(n-1),再减去那些上一位为D的情况,而这个值不正就是路径数为n-1时的答案吗。所以我们得出了递推公式为 

a_n=3^{n-1}-a_(_n_-_1_)  , a_1=0, a_2=2 

但是有一个问题是n的取值范围为10^7,3^100达到了48位,远超long long int 范围,这里就有一个求余的运算特点需要补充,每算一次×3就应该取一次余,也会得出正确答案,且保证了位数不会超过范围。

模运算知识补充:

模运算与基本四则运算有些相似,但是除法例外。其规则如下:
(a + b) % p = (a % p + b % p) % p (1)
(a - b) % p = (a % p - b % p ) % p (2)
(a * b) % p = (a % p * b % p) % p (3)
a ^ b % p = ((a % p)^b) % p (4)
结合律:((a+b) % p + c) % p = (a + (b+c) % p) % p (5)
((a*b) % p * c)% p = (a * (b*c) % p) % p (6)
交换律:(a + b) % p = (b+a) % p (7)
(a * b) % p = (b * a) % p (8)
分配律:(a+b) % p = ( a % p + b % p ) %p(9)
((a +b)% p * c) % p = ((a * c) % p + (b * c) % p) % p (10)

解法二:

公式法简单粗暴         (图从别的朋友扒拉来的,不过网上貌似都是这种做法)

可能是可以列一个过程发现规律,那个3*是上两步以D为节点的有三种选择ABC,不会进入D,上一步以D为结尾的不可以再进入D,但是和它同级的有另外两个不是D的结点他们都可以进入D,因此为dp[n-1]*2+dp[i-2]*3;而且要注意的是每一步也要对10^9+7取模。

附上简陋的图示:

               

还有另一种推出公式的方式为通过递推公式求出,显然是一道数学问题,easy可以解决。

代码

#include<iostream>
#include<cmath>
using namespace std;
long long int a[10000002]={0};
int main()
{
    int n=0;
    a[0]=0;
    a[1]=0;
    a[2]=3;
    a[3]=6;
    cin>>n;
    long long int num=9;
    for(int i=4;i<=n;i++)
    {
        num=num*3%(1000000000+7);
        a[i]=(num-a[i-1]+1000000000+7)%(1000000007);
    }
    cout<<a[n]%(1000000000+7)<<endl;
    return 0;
}

 

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值