We all know that GukiZ often plays with arrays.
Now he is thinking about this problem: how many arrays a, of length n, with non-negative elements strictly less then 2l meet the following condition: ? Here operation means bitwise AND (in Pascal it is equivalent to and, in C/C++/Java/Python it is equivalent to &), operation means bitwise OR (in Pascal it is equivalent to , in C/C++/Java/Python it is equivalent to |).
Because the answer can be quite large, calculate it modulo m. This time GukiZ hasn't come up with solution, and needs you to help him!
First and the only line of input contains four integers n, k, l, m (2 ≤ n ≤ 1018, 0 ≤ k ≤ 1018, 0 ≤ l ≤ 64, 1 ≤ m ≤ 109 + 7).
In the single line print the number of arrays satisfying the condition above modulo m.
2 1 2 10
3
2 1 1 3
1
3 3 2 10
9
In the first sample, satisfying arrays are {1, 1}, {3, 1}, {1, 3}.
In the second sample, only satisfying array is {1, 1}.
In the third sample, satisfying arrays are {0, 3, 3}, {1, 3, 2}, {1, 3, 3}, {2, 3, 1}, {2, 3, 3}, {3, 3, 0}, {3, 3, 1}, {3, 3, 2}, {3, 3, 3}.
题意:给了一个长整数k,问用n个不超过2^l的数做((a1&a2)|(a2&a3)...|(an-1&an))的运算,有多少种情况等于k
分析:这道题很难QWQ...首先n个数相与是这n个数每个数位都要与,我把这n个数位当成一个数看,如果相邻两个不同时为1,最终得到的这一位就是0,反之为1。那么如何算这些一个长度为n位的二进制数有多少个不相邻的1呢?我们令dp[n]表示长度为n的二进制数不相邻的1的个数,第n位为1时,第n-1位一定不为1,否则结果就是1了,相当于第n-1位是0有多少种情况,就是dp[n-2]种,第n位是0时,第n-1位都可以,有dp[n-1]种,所以dp[n] = dp[n-1] + dp[n-2]。反之,该位最终得到1的情况就是2^n-dp[n]种。然后结合k每一位是0还是1,(注意最多不超过l位,最多的情况就是l位数),乘以种数得到答案
注意本题坑点,取模的数为1,2^63溢出,得开unsigned long long
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<stack>
#define maxn 2
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
const int N = 100010;
const int INF = 0x3f3f3f3f;
ll mod ;
typedef struct
{
ll m[maxn][maxn];//注意长整型
}Matrix;
Matrix I = {1,0,
0,1, };
Matrix mul(Matrix a,Matrix b)
{
Matrix c;
for(int i = 0; i < maxn; i++)
for(int j = 0; j < maxn; j++)
{
c.m[i][j] = 0;
for(int k = 0; k < maxn; k++)
{
c.m[i][j] += (a.m[i][k] * b.m[k][j]) % mod;//这句写错了
c.m[i][j] %= mod;
}
}
return c;
}
Matrix quickpow(Matrix a,ll n)
{
Matrix m = a;
Matrix b = I;
while(n > 0)
{
if(n & 1)
b = mul(m,b);
m = mul(m , m);
n >>= 1;
}
return b;
}
ll mod_pow(ll x, ll n, ll mod)
{
ll res = 1;
while(n > 0)
{
if(n & 1)res = res * x % mod;//如果二进制最低位为1就乘上x ^(2^i)
x = x * x % mod;//将X平方,因为每移一位就相当于指数乘以2
n >>= 1;
}
return res;
}
int main()
{
ll n,k,l;
cin>>n>>k>>l>>mod;
if((l != 64 && (k >= ((ull)1 << (ull)l))) || (mod == 1))
{
printf("0\n");
return 0;
}
Matrix re;
re.m[0][0] = 1;re.m[0][1] = 1;
re.m[1][0] = 1;re.m[1][1] = 0;
re = quickpow(re,n);
ll x = re.m[0][0] + re.m[1][0];
ll y = ((mod_pow((ll)2,n,mod) - x) % mod + mod) % mod;//注意减法的写法
ll sum = 1;
for(ll i = 0; i < l; i++)
{
if(k & (1LL << i))sum = (sum * y) % mod;
else sum = (sum * x) % mod;
}
cout<<sum<<endl;
return 0;
}