題意
給定n,l,k,m
,假設一個長度爲n的數組a,滿足a[i] < (a[1] and a[2])or(a[2] and a[3]) or ... (a[n-1] and a[n]) = k
。問這樣子的數組的個數有多少,答案模m。
思路
首先這道題我們要通過二進制位來計算。我們可以知道,對於每個位,可以獨立計算。然後我們就可以計算每個位是0的種數。設dpi是長度爲i的序列爲0的種數。可以推出,dp[i] = dp[i-1] + dp[i-2]
所以我們用矩陣快速冪去求出斐波那契數列的值,然後用一下乘法原理即可。
寫題解的原因是求斐波那契數列可以不用寫矩陣快速冪。我們可以設f[n] = x * f[n -k ] + y * f[n - k -1],對於k = n/2時解出xy的值。這樣我們就可以遞歸的去求解f[n],時間複雜度仍爲
AC代碼
/*************************************************************************
> File Name: pd.cpp
> Author: znl1087
> Mail: [email protected]
> Created Time: 六 6/20 09:11:46 2015
************************************************************************/
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <string>
#include <cstdlib>
#include <vector>
#include <set>
#include <map>
#define LL long long
using namespace std;
LL n,k,l,m;
LL pow2(LL x){
if( x == 1) return 2%m;
LL temp = pow2(x/2);
temp = (temp * temp)%m;
if( x & 1)temp = (temp * 2)%m;
return temp;
}
map<LL,LL> F;
LL fib(LL n){
if(F.count(n))return F[n];
LL k = n/2;
if(n % 2 == 0) return F[n] = ( fib(k) * fib(k) % m + fib(k-1) * fib(k-1) % m)%m;
else return F[n] = (fib(k) * fib(k+1) % m + fib(k-1) * fib(k) % m)%m;
}
int main(){
cin>>n>>k>>l>>m;
if( m == 1 || k >= (1ULL << min(l,63ll)) ){
cout<<0<<endl;
return 0;
}
F[0] = 1,F[1] = 1;
LL res = 1;
LL tot = pow2(n),zero = fib(n+1);
LL temp = (tot - zero + m)%m;
//cout<<tot<<endl;
for(int i=0;i<l;i++){
if(k & 1)res = res * temp % m;
else res = res * zero %m;
k>>=1;
}
cout<<res<<endl;
return 0;
}