UVA - 10518 How Many Calls? (构造矩阵,快速幂)
题意:
求f[n] = f[n-1] + f[n-2] + 1,在b(10000)进制下的最后一位数字的十进制表示。
思路:
构造矩阵即可,M矩阵是一个3_3的矩阵,M1矩阵是一个3_1的矩阵。。很easy,就不说了。
写题解的目的是,对于这种要求b进制下,最后一位或者最后两位的数字的十进制表示的问题,其实就是在说,取模的数是base或者base^2
1A美滋滋
/* ***********************************************
Author :111qqz
Created Time :2017年10月01日 星期日 18时39分17秒
File Name :10518.cpp
************************************************ */
1#include <cstdio>
2#include <cstring>
3#include <iostream>
4#include <algorithm>
5#include <vector>
6#include <queue>
7#include <set>
8#include <map>
9#include <string>
10#include <cmath>
11#include <cstdlib>
12#include <ctime>
13#define PB push_back
14#define fst first
15#define sec second
16#define lson l,m,rt<<1
17#define rson m+1,r,rt<<1|1
18#define ms(a,x) memset(a,x,sizeof(a))
19typedef long long LL;
20#define pi pair < int ,int >
21#define MP make_pair
1using namespace std;
2const double eps = 1E-8;
3const int dx4[4]={1,0,0,-1};
4const int dy4[4]={0,-1,1,0};
5const int inf = 0x3f3f3f3f;
6const int N = 5;
7LL n,base;
8struct Mat
9{
10 LL mat[N][N];
11 void clear()
12 {
13 ms(mat,0);
14 }
15}M,M1;
16Mat operator * ( Mat a,Mat b)
17{
18 Mat c;
19 c.clear();
20 for ( int i = 0 ; i < 3 ; i++)
21 for ( int j = 0 ; j < 3 ; j++)
22 for ( int k = 0 ; k < 3 ; k++)
23 c.mat[i][j] = (c.mat[i][j] + a.mat[i][k] * b.mat[k][j]% base)se;
return c;
}
1Mat operator ^ (Mat a,LL b)
2{
3 Mat ret;
4 ret.clear();
5 for ( int i = 0 ; i < 3 ; i++) ret.mat[i][i] = 1;
6 while (b>0)
7 {
8 if (b&1) ret = ret * a;
9 b = b >> 1LL;
10 a = a * a;
11 }
12 return ret;
13}
14LL solve()
15{
16 if (n==0) return 0;
17 if (n==1) return 1;
18 M.clear();
19 M1.clear();
20 M.mat[0][0] = M.mat[0][1] = M.mat[0][2] = 1;
21 M.mat[1][0] = M.mat[2][2] = 1;
22 M1.mat[0][0]=M1.mat[1][0]=M1.mat[2][0] = 1;
1 Mat ans;
2 ans.clear();
3 ans = (M ^ (n-1))*M1;
4 return ans.mat[0][0]se;
5}
1int main()
2{
3 #ifndef ONLINE_JUDGE
4 freopen("./in.txt","r",stdin);
5 #endif
6 int cas = 0 ;
7 while (~scanf("%lld %lld",&n,&base))
8 {
9 if (n==0&&base==0) break;
10 LL ans = solve();
11 printf("Case %d: %lld %lld %lld\n",++cas,n,base,ans);
12 }
1 #ifndef ONLINE_JUDGE
2 fclose(stdin);
3 #endif
4 return 0;
5}