http://codeforces.com/problemset/problem/226/A
题意:有①—②—③三个点如此连接。有n个数在位置③,要全部移动到位置①。数A可以从一个点移动到另一个点,当且仅当A大于这两个点的所有数。
题解:多写几个可以发现递推式:a[n]=3*a[n-1]+2。
法一:构造矩阵进行矩阵快速幂。
| a[n] 1 | | 3 0 |
| 0 0 | | 2 1 |
法二:等比数列求和:a[n]+1=3*(a[n-1]+1),所以a[n]=3^n-1。
矩阵快速幂:
#include<set>
#include<map>
#include<stack>
#include<queue>
#include<vector>
#include<string>
#include<bitset>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<iomanip>
#include<iostream>
#define debug cout<<"aaa"<<endl
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define MIN_INT (-2147483647-1)
#define MAX_INT 2147483647
#define MAX_LL 9223372036854775807i64
#define MIN_LL (-9223372036854775807i64-1)
using namespace std;
const int N = 2;
LL mod;
struct node{
LL m[N][N];
};
node Mul(node a,node b){
node c;
mem(c.m,0);
for(int k=0;k<N;k++){
for(int i=0;i<N;i++){
if(a.m[i][k]){
for(int j=0;j<N;j++){
c.m[i][j]=(c.m[i][j]+(a.m[i][k]*b.m[k][j])%mod+mod)%mod;
}
}
}
}
return c;
}
node quickmod(node a,LL b){
node res;
mem(res.m,0);
for(int i=0;i<N;i++){
res.m[i][i]=1;
}
while(b){
if(b&1){
res=Mul(res,a);
}
a=Mul(a,a);
b>>=1;
}
return res;
}
int main(){
LL n;node a,b,ans;
cin>>n>>mod;
mem(a.m,0),mem(b.m,0);
b.m[0][0]=0,b.m[0][1]=1;
a.m[0][0]=3,a.m[1][0]=2,a.m[1][1]=1;
a=quickmod(a,n);
ans=Mul(b,a);
cout<<ans.m[0][0]<<endl;
return 0;
}
等比数列:
#include<bits/stdc++.h>
#define debug cout<<"aaa"<<endl
#define d(a) cout<<a<<endl
#define mem(a,b) memset(a,b,sizeof(a))
#define LL long long
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define MIN_INT (-2147483647-1)
#define MAX_INT 2147483647
#define MAX_LL 9223372036854775807i64
#define MIN_LL (-9223372036854775807i64-1)
using namespace std;
const int N = 100000 + 5;
const int mod = 1000000000 + 7;
const double eps = 1e-8;
LL quickMod(LL a,LL b,LL m){
LL ans=1;
a%=m;
while(b){
if(b&1)
ans=(ans*a)%m;
a=(a*a)%m;
b>>=1;
}
return ans;
}
int main(){
LL n,m,ans;
cin>>n>>m;
ans=quickMod(3,n,m)-1;
ans=(ans+m)%m;
cout<<ans<<endl;
return 0;
}