So happy!(get 矩陣快速冪)ICPC :E HDU 6198

  1. number number number
  2. Time Limit: 2000/1000 MS (Java/Others) Memory
    Limit: 32768/32768 K (Java/Others) Total Submission(s): 637

    Accepted Submission(s): 407
    Problem Description We define a sequence F:

    ⋅ F0=0,F1=1; ⋅ Fn=Fn−1+Fn−2 (n≥2).

    Give you an integer k, if a positive number n can be expressed by
    n=Fa1+Fa2+…+Fak where 0≤a1≤a2≤⋯≤ak, this positive number is
    mjf−good. Otherwise, this positive number is mjf−bad. Now, give you
    an integer k, you task is to find the minimal positive mjf−bad
    number. The answer may be too large. Please print the answer modulo

  3. Input There are about 500 test cases, end up with EOF. Each test case
    includes an integer k which is described above. (1≤k≤109)

    Output For each case, output the minimal mjf−bad number mod

  4. Sample Input

    1

    Sample Output

    4
    Source 2017 ACM/ICPC Asia Regional Shenyang Online

    前提:矩陣快速冪+斐波那契數列推薦題目(poj3070(斐波那契的矩陣表示))
    思路:
    * 題目要求找bad number,枚舉錢四項分別是 4,12,33,88,斐波那契數列爲0 , 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89*
    對應的下標分別是0,1,2,3,4,5,6,7,8,9,10,11
    第一個bad number: 4=f4+f3-1;
    第二個bad number :12=f5+f6-1;
    第三個bad number: 33 =f7+f8-1;
    * 因而推導出一下公式: a(n)=f(2*n+2)+f(2*n+1)-1*

代碼如下:

#include <bits/stdc++.h>
using namespace std;
const int mod =998244353;
struct matrix
{
   long long  int a[2][2];
};
matrix multply(matrix x,matrix y)
{
    matrix result ;
    memset(result.a,0,sizeof(result.a));
    int i,j,k;
    for (i=0;i<2;i++)
    for (j=0;j<2;j++)
    for (k=0;k<2;k++)
    {
        result.a[i][j]+=x.a[i][k]*y.a[k][j];
        if(result.a[i][j]>=mod)
        result.a[i][j]%=mod;
    }
    return result;
}
matrix pow_mod (matrix a,int n)
{
    matrix result;
    memset(result.a,0,sizeof(result.a));
    for (int i=0;i<2;i++)
    result.a[i][i]=1;
    while (n)
    {
        if(n&1)
         result=multply(result,a);
         a=multply(a,a);
         n>>=1;
    }
    return result ;

}

int main ()
{
    long long int n;
    while (cin>>n)
    {
         n=2*n+1;
         long long  int ans;
         matrix a;
         a.a[0][0]=a.a[0][1]=a.a[1][0]=1;
         a.a[1][1]=0;
         a=pow_mod(a,n);
         ans =a.a[0][0]+a.a[0][1]-1;
//         int i,j;
//         for (i=0;i<2;i++)
//         for (j=0;j<2;j++)
//         if(!j)
//         cout<<a.a[i][j]<<" ";
//         else
//         cout <<a.a[i][j]<<endl;
         if(ans>=mod)
         ans%=mod;
         cout<<ans<<endl;
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章