Number Sequence(HDU 1005 构造矩阵 )

Number Sequence

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


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).
 
 
Sample Input
1 1 3
1 2 1
0 0 0 0
 
Sample Output
2
5
 因为数据量比较大,可以打表找到循环规律,但这种类型的题发现都可以构造矩阵求解
f[n]      =  a  b   *   f[n-1]
f[n-1]                  1  0    f[n-2]
 
 
 1 #include <iostream>
 2 #include <cstring>
 3 #include <cstdio>
 4 #include <algorithm>
 5 using namespace std;
 6 int a,b,n;
 7 int m[1000];
 8 struct Matrix
 9 {
10     int mat[2][2];
11 }p;
12 Matrix mul(Matrix a,Matrix b)
13 {
14     Matrix c;
15     for(int i=0;i<2;i++)
16     {
17         for(int j=0;j<2;j++)
18         {
19             c.mat[i][j]=0;
20             for(int k=0;k<2;k++)
21                 c.mat[i][j]=(c.mat[i][j]+a.mat[i][k]*b.mat[k][j])%7;
22         }
23     }
24     return c;
25 }
26 Matrix mod_pow(Matrix x,int n)
27 {
28     Matrix res;
29     memset(res.mat,0,sizeof(res.mat));
30     for(int i=0;i<2;i++)
31         res.mat[i][i]=1;
32     while(n)
33     {
34         if(n&1)
35             res=mul(res,x);
36         x=mul(x,x);
37         n>>=1;
38     }
39     return res;
40 }
41 int main()
42 {
43     freopen("in.txt","r",stdin);
44     while(scanf("%d%d%d",&a,&b,&n)!=EOF)
45     {
46         if(a==0&&b==0&&n==0)
47             break;
48         if(n<2)
49         {
50             printf("1\n");
51             continue;
52         }
53         p.mat[0][0]=a;
54         p.mat[1][0]=1;
55         p.mat[0][1]=b;
56         p.mat[1][1]=0;
57         Matrix ans= mod_pow(p,n-2);
58         printf("%d\n",(ans.mat[0][0]+ans.mat[0][1])%7);
59     }
60 }

 

 

 

posted @ 2016-05-06 11:44  御心飞行  阅读(310)  评论(0编辑  收藏  举报