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
  • 相关阅读:
    Longest Valid Parentheses
    [转载]ios入门篇 -hello Word(1)
    EXTJS 4 动态grid
    Spring AOP JPA
    Jchart 演示
    HSQLDB JPA GeneratedValue
    Antlr 练习
    回火方程
    URL decode 解决中文目录的乱码问题
    Arduino IIC lcd1602
  • 原文地址:https://www.cnblogs.com/xiaotian-222/p/5039629.html
Copyright © 2011-2022 走看看