UVA 10655 Contemplation! Algebra

 

通过计算得到递推公式

直接递推计算应会超时(未尝试),比较好的方法是转换为矩阵之后用矩阵快速幂优化。

即,n>=1,

 

另外,需要注意输入的结束,“Input is terminatedby a line containing only two zeroes. ”

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <map>
 4 #include <vector>
 5 #include <functional>
 6 #include <string>
 7 #include <cstring>
 8 #include <queue>
 9 #include <set>
10 #include <cmath>
11 #include <cstdio>
12 using namespace std;
13 #define IOS ios_base::sync_with_stdio(false)]
14 typedef long long LL;
15 const int INF=0x3f3f3f3f;
16 
17 const int maxn=2;
18 typedef struct matrix{
19     LL v[maxn][maxn];
20     void init(){memset(v,0,sizeof(v));}
21 }M;
22 M mul(const M &a,const M &b,int L,int m,int n)
23 {
24     M c; c.init();
25     for(int i=0;i<L;i++){
26         for(int j=0;j<n;j++){
27             for(int k=0;k<m;k++)//注意j,k范围
28                 c.v[i][j]+=a.v[i][k]*b.v[k][j];
29         }
30     }
31     return c;
32 }
33 M power(M x,int L,LL p)
34 {
35     M tmp; tmp.init();
36     for(int i=0;i<L;i++)
37         tmp.v[i][i]=1;
38     while(p){
39         if(p&1) tmp=mul(x,tmp,L,L,L);
40         x=mul(x,x,L,L,L);
41         p>>=1;
42     }
43     return tmp;
44 }
45 int main()
46 {
47     LL p,q,n;
48     M s,t;
49     while(scanf("%lld%lld%lld",&p,&q,&n)==3){
50         if(n==0) {puts("2");continue;};
51         s.init();
52         s.v[0][0]=p;
53         s.v[1][0]=2;
54         t.init();
55         t.v[0][0]=p;
56         t.v[0][1]=-q;
57         t.v[1][0]=1;
58         t=power(t,2,n-1);
59         t=mul(t,s,2,2,1);
60         printf("%lld\n",t.v[0][0]);
61     }
62 }

 

posted @ 2016-07-22 13:10  Cumulonimbus  阅读(188)  评论(0编辑  收藏  举报