HDU 1588-Gauss Fibonacci(矩阵快速幂+二分求矩阵和)

2015-07-20 17:12:03 ? 作者: ? 浏览: 3

Gauss Fibonacci Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & %I64u Submit Status Practice HDU 1588 Appoint description:

Description

Without expecting, Angel replied quickly.She says: "I'v heard that you'r a very clever boy. So if you wanna me be your GF, you should solve the problem called GF~. "
How good an opportunity that Gardon can not give up! The "Problem GF" told by Angel is actually "Gauss Fibonacci".
As we know ,Gauss is the famous mathematician who worked out the sum from 1 to 100 very quickly, and Fibonacci is the crazy man who invented some numbers.

Arithmetic progression:
g(i)=k*i+b;
We assume k and b are both non-nagetive integers.

Fibonacci Numbers:
f(0)=0
f(1)=1
f(n)=f(n-1)+f(n-2) (n>=2)

The Gauss Fibonacci problem is described as follows:
Given k,b,n ,calculate the sum of every f(g(i)) for 0<=i The answer may be very large, so you should divide this answer by M and just output the remainder instead.

Input

The input contains serveral lines. For each line there are four non-nagetive integers: k,b,n,M
Each of them will not exceed 1,000,000,000.

Output

For each line input, out the value described above.

Sample Input

 2 1 4 100
2 0 4 100 

Sample Output

 21
12 


这道题和poj3233的解题思路差不多,不过这道题需要自己推出规律来,还是太弱了,我怎么也认为输出的和应该是左上角的值,结果怎么也不对,最后去看了题解,看到输出的是右上角,然后看了人家写的题解思路,瞬间懂了。sadddddd

点击打开链接(附上巨巨博客)。用于构造斐波那契的矩阵为1 1

1 0

#include 
   
    
#include 
    
      #include 
     
       #include 
      
        #include 
       
         #include 
        
          #include 
         
           #include 
           #include 
           
             using namespace std; const int inf=0x3f3f3f3f; long long mod; struct node { long long mp[3][3]; }init,res1,res2,res; struct node Mult(struct node x,struct node y) { int i,j,k; struct node tmp; for(i=0;i<2;i++) for(j=0;j<2;j++){ tmp.mp[i][j]=0; for(k=0;k<2;k++){ tmp.mp[i][j]=(tmp.mp[i][j]+x.mp[i][k]*y.mp[k][j])%mod; } } return tmp; }; struct node expo(struct node x,int k) { struct node tmp; int i,j; for(i=0;i<2;i++) for(j=0;j<2;j++){ if(i==j) tmp.mp[i][j]=1; else tmp.mp[i][j]=0; } while(k){ if(k&1) tmp=Mult(tmp,x); x=Mult(x,x); k>>=1; } return tmp; }; struct node add(struct node x,struct node y) { struct node tmp; int i,j; for(i=0;i<2;i++) for(j=0;j<2;j++) tmp.mp[i][j]=(x.mp[i][j]+y.mp[i][j])%mod; return tmp; }; struct node sum(struct node x,int k) { struct node tmp; if(k==1) return x; if(k&1) return add(sum(x,k-1),expo(x,k)); tmp=sum(x,k/2); return add(tmp,Mult(tmp,expo(x,k/2))); }; int main() { int k,b,n; while(~scanf("%d %d %d %lld",&k,&b,&n,&mod)){ init.mp[0][0]=1; init.mp[0][1]=1; init.mp[1][0]=1; init.mp[1][1]=0; res1=expo(init,b); res2=expo(init,k); res=add(res1,Mult(res1,sum(res2,n-1))); printf("%lld\n",res.mp[0][1]); } return 0; } 
           
         
        
       
      
     
    
   



-->

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: