https://s3.amazonaws.com/codechef_shared/download/translated/SEPT15/mandarin/CODECRCK.pdf
PROBLEM LINK:
DIFFICULTY:
Easy-Medium
PREREQUISITES:
Math
PROBLEM:
Given two sequences a and b and a recurrence to calculate ai and bi , we need to calculate a certain value c when a pair of corresponding terms of a and b are given.
EXPLANATION:
Subtask 1
For subtask 1, we can simply iterate from
i
to
k
(as the case may be) and use the recurrences to calculate
ak
and
bk
.
Now, there are two cases:
-
When i≤k .
In this case, the given recurrence can be used directly. I.e.,
an+1=x(an+bn)−xy(an−bn)
bn+1=x(an−bn)+xy(an+bn) -
When k<i .
In this case, the following recurrence can be derived and used.
an−1=an+bn−y(an−bn)2x+2xy2
bn−1=an−bn+y(an+bn)2x+2xy2
The last step is to calculate 2s . The calculation must be done in floating type to ensure that the answer doesn't overflow. The in-built exponentiation function in most of the programming languages can do this job easily.
Subtask 2
Let us look at the original recurrences given to us, i.e.,
an+1=x(an+bn)−xy(an−bn)
bn+1=x(an−bn)+xy(an+bn)
What do they tell us? Basically, we are given an+1 and bn+1 in terms of an and bn . Let us go a step further and try to calculate an+2 and bn+2 in terms of an and bn .
For doing this, we first note the following terms:
an+1+bn+1=2xan+2xybn
an+1−bn+1=2xbn−2xyan
Now, we use our original recurrence to calculate
an+2
and
bn+2
.
an+2=x(2xan+2xybn)−xy(2xbn−2xyan)=an(2x2+2x2y2)
bn+2=x(2xbn−2xyan)+xy(2xan+2xybn)=bn(2x2+2x2y2)
Since,
x=2√
and
y=3√
, thus,
(2x2+2x2y2)=16
.
This leads us to a very important observation:
an+2=16an
bn+2=16bn
It tells us that if
i
and
k
are both even or both odd, then
ak+bk=c(ai+bi)
, where
c
is a constant. When
k−i=2
,
c=24
; when
k−i=4
,
c=28
, and so on. Thus,
c=22(k−i)
.
When
i
and
k
are of different parities, i.e., one is even and the other is odd, we can first calculate
ai+1
and
bi+1
and then calculate
ak
and
bk
.
The last part is to calculate 2s , which has already been explained in subtask 1.
COMPLEXITY:
All the operations take constant time except the use of exponentiation function. The in-built exponentiation function is implimented as
O(logN)
algorithm in all the programming languages.
Net complexity:
O(logN)
.
SAMPLE SOLUTIONS:
#include<bits/stdc++.h>
using namespace std;
int main() {
int i, k, s;
scanf("%d%d%d", &i, &k, &s);
int ai, bi;
scanf("%d%d", &ai, &bi);
double a = ai, b = bi;
if ((i&1) != (k&1)) {
i++;
a = sqrt(2.0) * ((ai + bi) - sqrt(3.0) * (ai - bi));
b = sqrt(2.0) * ((ai - bi) + sqrt(3.0) * (ai + bi));
}
double ans = (a + b) * pow(2.0, 2*(k-i) - s);
printf("%.10f\n", ans);
}