思路: 矩阵快速幂
分析:
1 题目要求的是求F(n)中如果位数的个数大于8那么要输出前4四位和后四位,没有到8位的时候直接输出
2 根据题目的样例我们可以知道当n = 40的时候就超过8位了,所以我们可以知道n <= 39的时候直接去求F(n),超过40的时候我们就要去求前4位和后四位
3 我们利用矩阵快速幂可以很快的求出后四位,但是前面四位就很困难了
下面看一下网上的解法:转载自点击打开链接
代码:
/************************************************
* By: chenguolin *
* Date: 2013-08-24 *
* Address: http://blog.youkuaiyun.com/chenguolinblog *
***********************************************/
#include<cmath>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long int64;
const int N = 2;
int64 n , MOD;
struct Matrix{
int64 mat[N][N];
Matrix operator*(const Matrix &m)const{
Matrix tmp;
for(int i = 0 ; i < N ; i++){
for(int j = 0 ; j < N ; j++){
tmp.mat[i][j] = 0;
for(int k = 0 ; k < N ; k++){
tmp.mat[i][j] += mat[i][k]*m.mat[k][j]%MOD;
tmp.mat[i][j] %= MOD;
}
}
}
return tmp;
}
};
int Pow(Matrix& m){
if(n <= 1)
return n;
Matrix ans;
ans.mat[0][0] = 1 ; ans.mat[0][1] = 0;
ans.mat[1][0] = 0 ; ans.mat[1][1] = 1;
n--;
while(n){
if(n%2)
ans = ans*m;
n /= 2;
m = m*m;
}
return ans.mat[0][0]%MOD;
}
int main(){
Matrix m;
while(scanf("%lld" , &n) != EOF){
MOD = 1e4;
m.mat[0][0] = 1 ; m.mat[0][1] = 1;
m.mat[1][0] = 1 ; m.mat[1][1] = 0;
if(n <= 39){
MOD = 1e9;
printf("%d\n" , Pow(m));
}
else{
double tmp;
double s = (sqrt(5.0)+1.0)/2.0;
tmp = -0.5*log(5.0)/log(10.0)+((double)n)*log(s)/log(10.0);
tmp -= floor(tmp);
tmp = pow(10.0,tmp);
while(tmp < 1000)
tmp *= 10;
printf("%04d...%04d\n",(int)tmp , Pow(m));
}
}
return 0;
}