Codeforces 166E. 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).

推公式可得

f(n) = 3 + (3^n - 9) / 4 (n为偶)

f(n) = 6 + (3^n - 27) / 4 (n为奇)

然后运用快速幂和乘法逆元知识做

#include<iostream>
#include<cstring>
#include<cstdio>
#include <string>
#include <sstream>
#include <map>
#include <cmath>
#include <algorithm>
#include <iomanip>
#include <stack>
#include <queue>
#include <set>
using namespace std;
typedef long long LL;
#define MOD 1000000007
LL n;

LL Fast_Mod(LL a,LL n){
  LL res = 1,base = a;
  while (n){
    if (n & 1){
      res = (res * base) % MOD;
    }
    base = (base * base) % MOD;
    n >>= 1;
  }
  return res;
}

int main(){
  // freopen("test.in","r",stdin);

  cin >> n;
  LL invfac = Fast_Mod(4,MOD-2);
  // for (n = 1; n <= 10; n++) {
  if (n % 2){
    cout << (6 + ((Fast_Mod(3,n) - 27 + MOD) % MOD) * invfac % MOD + MOD) % MOD;
  }
  else {
    cout << (3 + ((Fast_Mod(3,n) - 9 + MOD) % MOD) * invfac % MOD + MOD) % MOD;
  }
  //  cout << endl;}
  return 0;
}
View Code
原文地址:https://www.cnblogs.com/ToTOrz/p/7071100.html