CodeForces - 441E:Valera and Number (DP&数学期望&二进制)
Valera is a coder. Recently he wrote a funny program. The pseudo code for this program is given below:
//input: integers x, k, p
a = x;
for(step = 1; step <= k; step = step + 1){
rnd = [random integer from 1 to 100];
if(rnd <= p)
a = a * 2;
else
a = a + 1;
}
s = 0;
while(remainder after dividing a by 2 equals 0){
a = a / 2;
s = s + 1;
}
Now Valera wonders: given the values x, k and p, what is the expected value of the resulting number s?
Input
The first line of the input contains three integers x, k, p (1 ≤ x ≤ 109; 1 ≤ k ≤ 200; 0 ≤ p ≤ 100).
OutputPrint the required expected value. Your answer will be considered correct if the absolute or relative error doesn't exceed 10 - 6.
Examples1 1 50
1.0000000000000
5 3 0
3.0000000000000
5 3 25
1.9218750000000
题意:给定X,现在进行K轮操作,每一轮有P%的概率加倍,(100-P)%的概率加一,问K轮之后的X的因子2的次数。
思路:首先一个数X中2的因子个数=转化为二进制后末尾0的个数=__builtin_ctz(X);题解给的四维DP比较麻烦,这里有一种比较难以想到,但是不难理解的二维DP。
用dp[i][j],表示X+j进行i轮操作后的因子2的幂。 那么答案就是dp[K][0];
那么转移就是:
dp[i][j]+=(dp[i-1][j+1])*(1.0-P); 即第一次操作为+1;
dp[i][j<<1]+=(dp[i-1][j]+1)*P; 即第一次操作为*2;
虽然乘法的话第二维会加倍增长,但加法的话第二维会减小1,所以最小影响到dp[K][0]的最大第二维就是K,而不用维护所有的dp[][j],即j<=K;
#include<bits/stdc++.h> #define rep(i,a,b) for(int i=a;i<=b;i++) using namespace std; //*2 P double dp[210][410],P; int main() { int X,K; scanf("%d%d%lf",&X,&K,&P); P/=100.0; rep(i,0,K) dp[0][i]=__builtin_ctz(X+i); rep(i,1,K){ rep(j,0,K){ dp[i][j]+=(dp[i-1][j+1])*(1.0-P); dp[i][j<<1]+=(dp[i-1][j]+1)*P; } } printf("%.10lf\n",dp[K][0]); return 0; }