-
Notifications
You must be signed in to change notification settings - Fork 0
/
UVA 1177 - A General Recurrence Relation Solution
76 lines (68 loc) · 1.32 KB
/
UVA 1177 - A General Recurrence Relation Solution
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<bits/stdc++.h>
using namespace std;
#define ll long double
#define endl '\n'
long double temp[2][2];
const ll M=1000000000;
void ready()
{
// freopen("f.txt","r","stdin")
ios_base::sync_with_stdio(false);
cin.tie(0);
cout.tie(0);
}
void mat_multiply(long double a[2][2],ll b[2][2])
{
long double c[2][2];
for(int i=0; i<2; i++)
{
for(int j=0; j<2; j++)
{
c[i][j]=0.0;
for(int k=0;k<2;k++)
c[i][j]=c[i][j]+a[i][k]*b[k][j];
}
}
for(int i=0; i<2; i++)
for(int j=0; j<2; j++)
a[i][j]=c[i][j];
}
void mat_pow(ll mat[2][2],long long m)
{
if(m==1)
return;
mat_pow(mat,m/2);
mat_multiply(mat,mat);
if(m%2)
mat_multiply(mat,temp);
}
int main()
{
ready();
long long t,f0,f1,n;
long double a,b;
cin>>t;
while(t--)
{
cin>>f0>>f1>>a>>b>>n;
long double mat[2][2]= {{a,b},{1,0}};
temp[0][0]=a,temp[0][1]=b;
temp[1][0]=1,temp[1][1]=0;
if(n==0)
cout<<f0<<endl;
else if(n==1)
cout<<f1<<endl;
else
{
mat_pow(mat,n-1);
cout<<fixed<<setprecision(0)<<(mat[0][0]*f1+mat[0][1]*f0)<<endl;
}
}
return 0;
}
/*
3
0 1 1 1 20
0 1 -1 0 1000000000
-1 1 4 -3 18
*/