Problem Author: | Hadi Takla (TaklaOI) |
Prepared by: | Hadi Takla (TaklaOI) |
Edited by: | Hadi Takla (TaklaOI) |
Solution
Fact : An index in the original array can have any index (1\le j \le i) in the subsequence.
if we want the index to have the index in the subsequence , we should choose j-1 element from the i-1 elements before , and we can choose as we want from the next n-i elements.
so the number of the subsequences that have the index in the original array as in the subsequence is.
so we can calculate the answer using the formula.
but that's an \mathcal{O}(n^2) solution which cannot pass the constraints.
so let con_i = \sum_{j=1}^{i} \binom{i-1}{j-1} \cdot (-a_i)^j.
the answer will be
.
Now , let's write con_i as follows.
So we can split even indices alone and odd one alone.
so we can write con_i = even_i - odd_i
where even_i is the sum on even values , and odd_i is the sum on odd values.
now let's try to simplify even_i and odd_i.
when is even , j-1 is odd.
so if we let 2k + 1 = j-1 j = 2k + 2.
we can write even_i as follows:
which is equal to
.
now we can see that \sum_{k=0}^{\lfloor \frac{i-1}{2} \rfloor} \binom{i-1}{2k+1} \cdot a_i ^ {2k+1} is the sum of even places in a bionominal expansion which is equal to
so even_i will be equal to a_i \cdot \frac {(1 + a_i)^{i-1} - (1 - a_i)^{i-1}}{2}.
now the same way for odd_i.
when is odd, j-1 is even.
so if we let 2k = j-1 j = 2k + 1.
we can write odd_i as follows:
which is equal to
.
we can see that \sum_{k=0}^{\lfloor \frac{i-1}{2} \rfloor} \binom{i-1}{2k} \cdot a_i ^ {2k} is the sum of odd places in a bionominal expansion which is equal to.
so odd_i will be equal to a_i \cdot \frac {(1 + a_i)^{i-1} + (1 - a_i)^{i-1}}{2}.
returning to con_i = even_i - odd_i.
so con_i = a_i \cdot \frac {(1 + a_i)^{i-1} - (1 - a_i)^{i-1}}{2} - a_i \cdot \frac {(1 + a_i)^{i-1} + (1 - a_i)^{i-1}}{2}.
= -a_i \cdot (1-a_i)^{i-1}.
ans = \sum_{i=1}^{n} 2^{n-1} \cdot con_i.
.
Time complexity : \mathcal{O}(n \text{log}(\text{max}(a_i))).
#include<bits/stdc++.h>
#define endl '\n'
#define int long long
#define F first
#define S second
using namespace std;
const int N = 2e5 + 1;
const int M = 1e9 + 7;
int add(int a,int b)
{
a %= M;
b %= M;
return (a+b+M)%M;
}
int sub(int a,int b)
{
a %= M;
b %= M;
return (a-b+M)%M;
}
int mul(int a,int b)
{
a %= M;
b %= M;
int res = a*b;
res %= M;
res += M;
res %= M;
return res;
}
int pwr(int x,int y)
{
if(y == 0)
return 1;
int res = pwr(x,y/2);
res = mul(res,res);
if(y % 2)
res = mul(res , x);
return res;
}
int divi(int a,int b)
{
return mul(a , pwr(b,M-2));
}
signed main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
int tc = 1;
cin>>tc;
while(tc--)
{
int n;
cin>>n;
int ans = 0;
int a[n+1];
for(int i=1;i<=n;i++){
cin>>a[i];
int tmp = pwr(2 , n-i);
tmp = mul(tmp , a[i]);
tmp = mul(tmp , pwr(sub(1 , a[i]) , i-1));
tmp = mul(tmp , -1);
ans = add(ans , tmp);
}
cout<<ans<<endl;
}
}