组合概率

输入:从[a,b]中取出n个整数,求n个整数和为x的概率是多少。可以重复取出。

利用动态规划+枚举

#include

using namespace std;

double dp[110][11000];

int main()
{
    if(freopen("/Users/richard/ClionProjects/Didi/in","r",stdin) == NULL) {
        cout << "failed open!" << endl;
    }

    int n,a,b,x;
    double p;
    cin >> n >> a >> b >> x;

    memset(dp,0, sizeof(dp));

    p = 1.0f/(b-a+1);

    for(int i = 1; i <= n; ++i) {
        for(int j = a *i; j <= b*i && j <= x; ++j) {//i个数,其和的range为a*i~b*i
            if(i == 1) {
                dp[i][j] = p;
            } else {
                double pp = 0;
                for(int z = a; z <= b; ++z) {
                    if(j >= z)
                        pp += dp[i-1][j-z]*p;//动态规划dp
                }
                dp[i][j] = pp;
            }
        }
    }

    printf("%0.4f\n", dp[n][x]);

    return 0;
}



你可能感兴趣的:(随笔)