题目:https://www.smartoj.com/p/2297
题意:矩阵F[][]满足以下递推式
输入八个整数n,m,a,b,c,d,e,f,输出F[n][m]%2012182013的值。
分析:本题需要构造矩阵,那么首先我们根据递推式
可以构造
可以看出,我们还需要求F[n][2]和F[n][1]的值。那么继续,根据
我们先利用上面的式子消去下面式子中的F[i][1]得到
所以有矩阵
那么,与开始的矩阵连起来就得到
可以看出,这样就构成了关于n的矩阵递推关系。那么进一步得到
那么,我们再根据前面的关于m的矩阵递推下去得到
这样,我们就可以计算了,但是这里有一个问题,就是幂m和n会很大,那么对于矩阵,实际上是不能用费马小定理降幂的,那么我们有一种方法,叫做十进制快速幂。它的原理基本和二进制快速幂差不多,模拟一下就知道了,很容易的。
在SmartOJ上貌似评测机速度慢,得到的结果是TLE,连别人AC过的代码都T,也就只能这样了,关键是掌握方法即可。
#include <iostream>
#include <string.h>
#include <stdio.h>
#include <string>
using namespace std;
typedef long long LL;
const int N = 3;
const LL MOD = 2012182013;
string NN,MM,AA,BB,CC,DD,EE,FF;
struct Matrix
{
LL m[N][N];
};
Matrix I =
{
1,0,0,
0,1,0,
0,0,1
};
Matrix multi(Matrix a,Matrix b)
{
Matrix c;
for(int i=0; i<N; i++)
{
for(int j=0; j<N; j++)
{
c.m[i][j] = 0;
for(int k=0; k<N; k++)
{
c.m[i][j] += ((a.m[i][k] % MOD) * (b.m[k][j] % MOD)) % MOD;
c.m[i][j] %= MOD;
}
}
}
return c;
}
Matrix power(Matrix A,LL k)
{
Matrix ans = I, p = A;
while(k)
{
if(k&1)
{
ans = multi(ans,p);
k--;
}
k >>= 1;
p = multi(p,p);
}
return ans;
}
Matrix T_power(Matrix A,string str) //十进制快速幂
{
int len = str.length();
Matrix ans = I, p = A;
while(len != 0)
{
int k = str[len-1] - '0';
ans = multi(ans,power(p,k));
p = power(p,10);
len--;
}
return ans;
}
LL Module(string str,LL MOD)
{
int len = str.length();
LL ans = 0;
for(int i=0; i<len; i++)
{
ans = ans * 10 + str[i] - '0';
ans %= MOD;
}
return ans;
}
void Sub(string &str,int x)
{
int len = str.length();
for(int i=len-1; i>=0; i--)
{
if(str[i] - '0' < x)
{
str[i] += 10 - x;
x = 1;
}
else
{
str[i] -= x;
x = 0;
}
}
if(str[0] == '0' && str.length() > 1)
str.erase(0,1);
}
int main()
{
while(cin>>NN>>MM>>AA>>BB>>CC>>DD>>EE>>FF)
{
LL a = Module(AA,MOD);
LL b = Module(BB,MOD);
LL c = Module(CC,MOD);
LL d = Module(DD,MOD);
LL e = Module(EE,MOD);
LL f = Module(FF,MOD);
Matrix A;
A.m[0][0] = b;
A.m[0][1] = a;
A.m[0][2] = c;
A.m[1][0] = 1;
A.m[1][1] = 0;
A.m[1][2] = 0;
A.m[2][0] = 0;
A.m[2][1] = 0;
A.m[2][2] = 1;
Sub(MM,2);
Matrix ans1 = T_power(A,MM);
Matrix B;
B.m[0][0] = (d + e * e % MOD) % MOD;
B.m[0][1] = d * e % MOD;
B.m[0][2] = (f + e * f % MOD) % MOD;
B.m[1][0] = e;
B.m[1][1] = d;
B.m[1][2] = f;
B.m[2][0] = 0;
B.m[2][1] = 0;
B.m[2][2] = 1;
Sub(NN,1);
Matrix ans2 = B;
Matrix ans = multi(ans1,ans2);
ans = T_power(ans,NN);
ans = multi(ans,ans1);
LL res = (ans.m[0][0] + ans.m[0][1]) % MOD;
res = (res + ans.m[0][2]) % MOD;
cout<<res<<endl;
}
return 0;
}
题目:http://218.28.19.228/cogs/problem/problem.php?pid=1397
题意:矩阵F[][]满足以下条件
求F[n][m]%1000000007的值。
分析:当然这个题做法实际上跟上面的题做法一样,用十进制快速幂就能AC,但是你会发现用费马小定理降幂同样对,在这里由于数据的特殊性恰好避开了使用费马小定理出错的情况,十进制快速幂才是正解。由于基本与上题一样,就不贴代码了。