zoukankan      html  css  js  c++  java
  • HDU 1005 矩阵快速幂

    Number Sequence

    Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
    Total Submission(s): 169273    Accepted Submission(s): 41762


    Problem Description
    A number sequence is defined as follows:

    f(1) = 1, f(2) = 1, f(n) = (A * f(n - 1) + B * f(n - 2)) mod 7.

    Given A, B, and n, you are to calculate the value of f(n).
     
    Input
    The input consists of multiple test cases. Each test case contains 3 integers A, B and n on a single line (1 <= A, B <= 1000, 1 <= n <= 100,000,000). Three zeros signal the end of input and this test case is not to be processed.
     
    Output
    For each test case, print the value of f(n) on a single line.
     
    Sample Input
    1 1 3 1 2 10 0 0 0
     
    Sample Output
    2 5
     
    Author
    CHEN, Shunbao
     
    Source
    题意:给你A B 求f(n) 
    题解:构造矩阵 矩阵快速幂
     1 #include<bits/stdc++.h>
     2 #define ll long long
     3 #define mod 7
     4 using namespace std;
     5 int A,B,n;
     6 struct node
     7 {
     8     int a[3][4];
     9 }exm,ans;
    10 struct node matrix_mulit(struct node aa,struct node bb)
    11 {
    12     struct node there;
    13     for(int i=0;i<2;i++)
    14     {
    15         for(int j=0;j<2;j++)
    16         {
    17             there.a[i][j]=0;
    18             for(int k=0;k<2;k++)
    19             {
    20                 there.a[i][j]=(there.a[i][j]+(aa.a[i][k]*bb.a[k][j]%mod))%mod;
    21             }
    22         }
    23     }
    24     return there;
    25 }
    26 int matrix_quick(int gg)
    27 {
    28     exm.a[0][0]=A;exm.a[0][1]=B;
    29     exm.a[1][0]=1;exm.a[1][1]=0;
    30     ans.a[0][0]=1; ans.a[0][1]=0;
    31     ans.a[1][0]=1; ans.a[1][1]=0;
    32     while(gg)
    33     {
    34         if(gg&1)
    35             ans=matrix_mulit(exm,ans);
    36         exm=matrix_mulit(exm,exm);
    37         gg>>=1;
    38     }
    39     return ans.a[0][0];
    40 }
    41 int main()
    42 {
    43     while(scanf("%d %d %d",&A,&B,&n)!=EOF)
    44     {
    45     if(A==0&&B==0&&n==0)
    46         break;
    47     if(n==1||n==2)
    48         printf("1
    ");
    49     else
    50         printf("%d
    ",matrix_quick(n-2));
    51     }
    52     return 0;
    53 }
  • 相关阅读:
    2018.11.26
    JS数组
    JS2018.12.26
    手机游戏客户端架构设计
    IAP应用内购买
    cocos2dx如何优化内存的应用
    Homebrew
    OS X 文档
    Apple推送通知服务教程
    ajax分页
  • 原文地址:https://www.cnblogs.com/hsd-/p/6665505.html
Copyright © 2011-2022 走看看