Codeforces 441E Valera and Number 概率DP

题目大意:

现在有如下的伪代码:

//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;
}

现在对于给定的x <= 10^9, k <= 200, 0 <= p <= 100求得到的s的期望值


大致思路:

感觉好难的一个概率DP...后来还是看了别人的题解AC掉的, CF官方题解是4维的DP表示不懂...看了一个大神的一个二维的题解..学习之


代码如下:

Result  :  Accepted     Memory  :  8 KB     Time  :  30 ms

/*
 * Author: Gatevin
 * Created Time:  2015/2/24 16:05:25
 * File Name: Codeforces_441E.cpp
 */
#include<iostream>
#include<sstream>
#include<fstream>
#include<vector>
#include<list>
#include<deque>
#include<queue>
#include<stack>
#include<map>
#include<set>
#include<bitset>
#include<algorithm>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cctype>
#include<cmath>
#include<ctime>
#include<iomanip>
using namespace std;
const double eps(1e-8);
typedef long long lint;

/*
 * (这里说的末尾0的个数指的都是对应的二进制后面连续0的个数)
 * 如果用dp[i][j]表示初始时将x加上j之后在第i次随机运行那个函数之后
 * 得到的末尾的连续的0的个数的期望
 * 初始化dp[0][0~k]为对应的x + j之后的末尾0的个数
 * 如果第i轮之后对于x + j的末尾的0的个数期望是dp[i][j]
 * 那么对于1 - p的可能性+1, 考虑对于i + 1轮的贡献可以发现
 * dp[i + 1][j] += dp[i][j + 1]*(1 - p)//这个+1可以是初始的时候的x+1
 * 对于*2的可能性有
 * dp[i + 1][j << 1] += (dp[i][j] + 1)*(1 - p)
 * 对于*2相当于初始的时候的x加的数翻倍了, 并且*2会导致末尾0的个数+1
 * 由于最多只有k次+1初始化的时候初始化dp[0][0~k]即可
 */
int x, k, p;
double dp[2][210];//滚动数组

int main()
{
    scanf("%d %d %d", &x, &k, &p);
    double P = p/100.;
    for(int i = 0; i <= k; i++)
    {
        int tmp = x + i;
        while(!(tmp & 1))
            tmp >>= 1, dp[0][i] += 1.;
    }
    int now = 0;
    for(int i = 0; i < k; i++)
    {
        memset(dp[now^1], 0, sizeof(dp[now^1]));
        for(int j = 0; j <= k; j++)
        {
            dp[now^1][j << 1] += (dp[now][j] + 1)*P;
            dp[now^1][j] += dp[now][j + 1]*(1 - P);
        }
        now ^= 1;
    }
    printf("%.10f\n", dp[now][0]);
    return 0;
}


你可能感兴趣的:(number,codeforces,and,概率DP,Valera,441E)