Codeforces 166E Tetrahedron(DP)

探讨了在一个四面体中,一只从顶点D出发的蚂蚁,如何在确切的n步内返回到顶点D的不同路径数量计算问题。通过递归公式与模运算解决路径数量的计算,避免大数问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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

感觉像是递推式,先DFS打表:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

#define mod 1000000007

int dp[21];

void dfs(int x,int step){
	if(step>10) return;
	if(x==0) dp[step]++;
	for(int i=0;i<4;i++){
		if(i!=x) dfs(i,step+1);
	}
}

int main(){
	memset(dp,0,sizeof(dp));
	dfs(0,0);
	for(int i=1;i<=10;i++){
		cout<<dp[i]<<endl;
	}
	return 0;
}

在这里插入图片描述
显然得到递推公式:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
using namespace std;

#define mod 1000000007

int main(){
	int n;
	cin>>n;
	long long x=0;
	for(int i=2;i<=n;i++){
		if(i&1) x=(x*3-3)%mod;
		else x=(x*3+3)%mod;
	}
	cout<<x<<endl;
	return
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值