zoukankan      html  css  js  c++  java
  • hdu 1005 Number Sequence(矩阵连乘+二分快速求幂)

    题目:
    http://acm.hdu.edu.cn/showproblem.php?pid=1005

    代码:

     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<string.h>
     4 #include<algorithm>
     5 using namespace std;
     6 const int mod=7;
     7 struct matrix
     8 {
     9   int f[2][2];
    10 };
    11 
    12 matrix mul(matrix a,matrix b)
    13 {
    14     int i,j,k;
    15     matrix c;
    16     memset(c.f,0,sizeof(c.f));
    17     for(i=0;i<2;i++)
    18     {
    19         for(j=0;j<2;j++)
    20         {
    21             for(k=0;k<2;k++)
    22             {
    23                 c.f[i][j]+=a.f[i][k]*b.f[k][j];
    24                 c.f[i][j]%=mod;
    25             }
    26         }
    27     }
    28     return c;
    29 }
    30 
    31 matrix pow_mod(matrix a,int b)
    32 {
    33     matrix s;
    34     int t;
    35     memset(s.f,0,sizeof(s.f));
    36     for(int i=0;i<2;i++)
    37     {
    38         s.f[i][i]=1;
    39     }
    40     while(b)
    41     {
    42         /*if(b&1)
    43         {
    44             s=mul(s,a);
    45         }
    46         a=mul(a,a);
    47         b=b>>1;*/
    48         t=b%2;
    49         b/=2;
    50         if(t!=0)
    51             s=mul(s,a);
    52          a=mul(a,a);
    53     }
    54     return s;
    55 }
    56 int main()
    57 {
    58     int a,b,n;
    59     while(scanf("%d%d%d",&a,&b,&n))
    60     {
    61         if(a==0&&b==0&&n==0)
    62             break;
    63          matrix e;
    64     e.f[0][0]=a;
    65     e.f[0][1]=1;
    66     e.f[1][0]=b;
    67     e.f[1][1]=0;
    68     e=pow_mod(e,n-1);
    69     printf("%d
    ",(e.f[0][1]+e.f[1][1])%mod);
    70     }
    71 
    72     return 0;
    73 }
    View Code
  • 相关阅读:
    2407: C语言习题 整数转换成字符串
    2484: 字母图形
    1658: Easier Done Than Said?
    Easier Done Than Said?(应用到的知识)
    1653: Champion of the Swordsmanship
    1614: 五位以内的对称素数
    1612: 最小公倍数
    $ vs $()
    数学
    计算机科学与技术课程
  • 原文地址:https://www.cnblogs.com/xiaotian-222/p/5039629.html
Copyright © 2011-2022 走看看