HDU 1005 Number Sequence(矩阵)

2018-06-17 22:01:34来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

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


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
ZJCPC2004
 

 

Recommend
 
JGShining   |   We have carefully selected several similar problems for you:  1008 1004 1021 1019 1002 
 
 
这道题需要推一个类似于斐波那契矩阵的矩阵。
比较好推

 

 

 1 #include<cstdio>
 2 #include<cstring>
 3 #include<iostream>
 4 using namespace std;
 5 const int MAXN=1001;
 6 inline void read(int &n){char c='+';bool flag=0;n=0;    
 7 while(c<'0'||c>'9') c=='-'?flag=1,c=getchar():c=getchar();    
 8 while(c>='0'&&c<='9') n=n*10+c-48,c=getchar();flag==1?n=-n:n=n;}
 9 struct matrix
10 {
11     int m[3][3];matrix(){memset(m,0,sizeof(m));}
12 };
13 matrix ma;
14 int limit=2;
15 const int mod=7;
16 matrix mul(matrix a,matrix b)
17 {
18     matrix c;
19     for(int k=0;k<limit;k++)
20         for(int i=0;i<limit;i++)
21             for(int j=0;j<limit;j++)
22                 c.m[i][j]=(c.m[i][j]+(a.m[i][k]*b.m[k][j]))%mod;
23     return c;
24 }
25 matrix fast_martix_pow(matrix ma,int p)
26 {
27     matrix bg;
28     bg.m[0][0]=1;bg.m[1][1]=1;
29     bg.m[0][1]=0;bg.m[1][0]=0;
30     /*for(int i=0;i<limit;i++)
31     {
32         for(int j=0;j<limit;j++)
33             cout<<bg.m[i][j]<<" ";
34         cout<<endl;
35     }*/
36         
37     while(p)
38     {
39         if(p&1)    bg=mul(bg,ma);
40         ma=mul(ma,ma);
41         p>>=1;
42     }
43     return bg;
44 }
45 int main()
46 {
47     int a,b,n;
48     while(scanf("%d%d%d",&a,&b,&n)&&(a!=0&&b!=0&&n!=0))
49     {
50         ma.m[0][0]=a;ma.m[0][1]=b;
51         ma.m[1][0]=1;ma.m[1][1]=0;
52         if(n<3)
53         {
54             printf("1\n");
55             continue;
56         }
57         matrix ans=fast_martix_pow(ma,n-2);
58         printf("%d\n",(ans.m[0][1]+ans.m[0][0])%mod);
59     }
60     return 0;
61 }

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:[最短路]P1078 文化之旅

下一篇:P3389 【模板】高斯消元法