Codeforces 992C(数学)
题面:
Nastya received a gift on New Year — a magic wardrobe. It is magic because in the end of each month the number of dresses in it doubles (i.e. the number of dresses becomes twice as large as it is in the beginning of the month).
Unfortunately, right after the doubling the wardrobe eats one of the dresses (if any) with the 50% probability. It happens every month except the last one in the year.
Nastya owns x dresses now, so she became interested in the expected number of dresses she will have in one year. Nastya lives in Byteland, so the year lasts for k + 1 months.
Nastya is really busy, so she wants you to solve this problem. You are the programmer, after all. Also, you should find the answer modulo 109 + 7, because it is easy to see that it is always integer.
The only line contains two integers x and k (0 ≤ x, k ≤ 1018), where x is the initial number of dresses and k + 1 is the number of months in a year in Byteland.
In the only line print a single integer — the expected number of dresses Nastya will own one year later modulo 109 + 7.
2 0
4
2 1
7
3 2
21
In the first example a year consists on only one month, so the wardrobe does not eat dresses at all.
In the second example after the first month there are 3 dresses with 50% probability and 4 dresses with 50% probability. Thus, in the end of the year there are 6 dresses with 50% probability and 8 dresses with 50% probability. This way the answer for this test is (6 + 8) / 2 = 7.
题目描述:
你拥有x个衣服,每个月这些衣服都会增加一倍,除了第k个月,其他月份均有50%的几率使得衣服的数量减少,问你在这k个月中,你获得衣服的数量的期望。
题目分析:
我们可以发现,衣服递增(增加两倍以及增加两倍再-1)的数量之间是可以构成一个二叉树结构的。
我们假设x=1的情况,我们可以得出以下这个图形:
紧接着,我们可以发现,第k个月的时候,累计出来的最终的数最大数为,且一共有个数满足条件,并且这个数是首项为,公差为-2的等差数列。
如下图:
而当x!=1的时候,剩余的数仍然是满足上述的这些性质,只不过我们需要在首项再乘上一个x,使得其变成首项为,公差为-2的等差数列。
此时我们对这个数列用等差数列的公式运算可得:
=
同时我们发现,因为每过一个月,就会有50%的几率发生发叉,因此,对于第k个月,我们的结果Sn需要再乘上
因此经过化简后的结果即为:
而因为我们所需要的结果是要mod上1e9+7的数,因此,对于所求的公式,我们也需要进行一些防止为0的措施,即公式为:
最后只需要带入快速幂计算即可。
代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
ll powmod(ll a,ll n){
int res=1;
while(n){
if(n&1){
res=res*a%mod;
}
a=a*a%mod;
n>>=1;
}
return res;
}
int main()
{
ll x,k;
cin>>x>>k;
if(x==0){
puts("0");
return 0;
}
cout<<(x%mod*powmod(2,k+1)%mod-powmod(2,k)+1+mod)%mod<<endl;
return 0;
}