【牛客】练习赛26 - B烟花(概率DP)

题目链接

题意:小a有个烟花,每个烟花代表着互不相同的颜色,对于第个烟花,它有的概率点燃,现在小a要去点燃它们,他想知道产生颜色的期望个数 及 产生恰好产生种颜色的概率 。

思路:概率DP 。
我们先看下面这个表格,是n为3,k为2的情况。

i\dp\j 0 1 2
0 1 0 0
1 1 p 1 p 1 0
2 ( 1 p 1 ) ( 1 p 2 ) ( 1 p 1 ) p 2 + p 1 ( 1 p 2 ) p 1 p 2
3 ( 1 p 1 ) ( 1 p 2 ) ( 1 p 3 ) ( 1 p 1 ) ( 1 p 2 ) p 3 + ( 1 p 1 ) p 2 ( 1 p 3 ) + p 1 ( 1 p 2 ) p 3 ( 1 p 1 ) p 2 p 3 + p 1 ( 1 p 2 ) p 3 + p 1 p 2 ( 1 p 3 )

可以看出来对于前i个烟花,恰好有j个燃放的概率只与前i-1个烟花,恰好有j个或j-1个燃放的概率有关。

设DP[i][j]表示前i个烟花恰好爆炸了j个的概率,可得DP方程:

{ D P [ i ] [ j ] = D P [ i 1 ] [ j ] ( 1 p i ) + D P [ i 1 ] [ j 1 ] p i D P [ 0 ] [ 0 ] = 1

AC代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
typedef long long ll;
typedef pair<int, int> pii;
inline int read(){int r=0;char c=getchar();while(c<'0'||c>'9') {c=getchar();}while(c>='0'&&c<='9') {r=r*10+c-'0';c=getchar();}return r;}
inline ll readll(){ll r=0;char c=getchar();while(c<'0'||c>'9') {c=getchar();}while(c>='0'&&c<='9') {r=r*10+c-'0';c=getchar();}return r;}
const double eps = 1e-8;
const double PI = acos(-1.0);
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
const int MAXN = 1e5;
const int MAXM = 1e5;

double dp[MAXN][233];
int main(int argc, char const *argv[])
{
    int n, k;
    double p, ans = 0;
    cin >> n >> k;
    dp[0][0] = 1;
    for(int i=1; i<=n; ++i){
        cin >> p;
        ans += p;
        dp[i][0] = dp[i-1][0]*(1.0-p);
        for(int j=1; j<=k;++j){
            dp[i][j] = dp[i-1][j]*(1.0-p)+dp[i-1][j-1]*p;
        }
    }
    printf("%.4lf\n%.4lf", ans, dp[n][k]);
    return 0;
}

这个DP方程的时间复杂度已经无法优化了,但是空间复杂度还可以从n*k优化成k。
我们用DP[i]表示在已经燃放了一下烟花后,恰好燃放了i个烟花的概率,重复利用DP数组。

但是有一点需要注意:我们更新DP时,需要从后向前更新,因为从前向后更新会将后面更新要用到的上一层的DP值覆盖。

AC代码:

#pragma GCC optimize(2)
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#include <ext/rope>
using namespace std;
using namespace __gnu_cxx;
typedef long long ll;
typedef pair<int, int> pii;
inline int read(){int r=0;char c=getchar();while(c<'0'||c>'9') {c=getchar();}while(c>='0'&&c<='9') {r=r*10+c-'0';c=getchar();}return r;}
inline ll readll(){ll r=0;char c=getchar();while(c<'0'||c>'9') {c=getchar();}while(c>='0'&&c<='9') {r=r*10+c-'0';c=getchar();}return r;}
const double eps = 1e-8;
//const double PI = acos(-1.0);
const ll INFLL = 0x3f3f3f3f3f3f3f3f;
const int INF = 0x3f3f3f3f;
const int mod = 1e9+7;
const int MAXN = 1e5;
const int MAXM = 1e5;

double dp[233];
int main(int argc, char const *argv[])
{
    int n, k;
    double p, ans = 0;
    cin >> n >> k;
    dp[0] = 1;
    for(int i=1; i<=n; ++i){
        cin >> p;
        ans += p;
        for(int j=k; j>=0; --j){
            dp[j] = dp[j]*(1.0-p)+dp[j-1]*p;
        }
    }
    printf("%.4lf\n%.4lf", ans, dp[k]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41009682/article/details/82561119
今日推荐