题解 HNU寒假训练赛1 之 A

227 阅读2分钟

声明:

题目来源:vjudge.net/contest/421…

此题解不一定所有题目都是本人独立完成,很有可能借鉴他人的算法,但代码一定由本人编写,决不复制粘贴。

题目1:Tetrahedron(四面体)

You are given a tetrahedron. Let's mark its vertices with letters A, B, C 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).

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

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

数据范围:1 ≤ n ≤ 10e7

输入样例:

2

4

输出样例:

3

21

解题思路:

设 f(n)为走了n步之后,走到顶点D的方法数。

设 g(n)为走了n步之后,走到除顶点D以外的A,B,C三点的方法数。

有递推公式:

f(n)=3g(n-1)

g(n)=2g(n-1)+f(n-1)

其中 f(1)=0, g(1)=1.

得 f(2)=3, f(3)=6, f(4)=21, f(5)=60...即为所求。

同时,每进行一步操作,结果对109 + 7取余。

题解:

#include<iostream>
#define lint long long
const lint base=1000000007;
using namespace std;

int main(){
	lint n;
	scanf("%lld",&n);
	lint f=0,g=1;  //f1 g1
	lint tf,tg;
	for(int i=1;i<n;i++){  //fn=3g(n-1) gn=f(n-1)+2g(n-1)
		tf=f,tg=g;
		f=3*tg%base;
		g=(tf+2*tg)%base;
	}
	printf("%lld\n",f);
	return 0;
}