codeforces 185A Plant(推公式)

Plant

【题目链接】Plant

【题目类型】推公式

&题解:

这个是可以推公式的:
每年的总个数是4^n个,设n年时向上的个数是x个,向下的个数是y个,那么n+1年时,向上的个数是3* x+y个,向下的个数是3* y+x个,这时你发现,如果他们两个相减,等于2* (x-y).x+y=4^n,2* (x-y)=4^(n+1)=4* 4^n.所以x-y=2* 4^n
所以(4n+2n)/2就是答案,但因为有取模的除法,所以要求2的逆元,又M是素数,所以用费马小定理就可以求逆元了.
参考逆元:点这里

&代码:

#include <cstdio>
#include <iostream>
#include <set>
#include <cmath>
#include <cstring>
#include <algorithm>
#include <map>
#include <queue>
#include <vector>
using namespace std;
#define INF 0x3f3f3f3f
using ll=long long;
const int maxn= 1e3 +9;
ll n,M=1000000007;
ll b_pow(ll x,ll i)
{
	ll ans=1;
	while(i>0){
		if(i&1)
			ans=(ans*x)%M;
		x=(x*x)%M;
		i>>=1;
	}
	return ans;
}
int main()
{
//	ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	freopen("E:1.txt","r",stdin);
	while(cin>>n){
		cout<<(b_pow(2,n)+b_pow(4,n))*b_pow(2,M-2)%M<<endl;
	}
	return 0;
}
原文地址:https://www.cnblogs.com/s1124yy/p/6606638.html