BZOJ3450 BZOJ4318 期望的线性性质

这两个题的套路是一样的,放在一起说。

3450:

因为期望有线性性质,也就是说我们可以分开算每一位的期望,再加起来就是答案。由于 E[(x+1)2x2]=2E[x]+1 E [ ( x + 1 ) 2 − x 2 ] = 2 E [ x ] + 1 ,所以我们只需要维护一个期望长度即可,维护的方法十分简单,相信聪明的你很快就能明白。

代码:

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pa pair<int,int>
const int Maxn=300010;
const int inf=2147483647;
int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return x*f;
}
int n;
char s[Maxn];
int main()
{
    n=read();
    scanf("%s",s+1);
    double len=0,ans=0;
    for(int i=1;i<=n;i++)
    {
        if(s[i]=='o')ans+=2.0*len+1,len+=1.0;
        else if(s[i]=='x')len=0.0;
        else ans+=(2.0*len+1)*0.5,len=(len+1.0)*0.5;
    }
    printf("%.4lf",ans);
}

4318:

由上一题的套路,有如下式子: E[(x+1)3x3]=E[3x2+3x+1]=3E[x2]+3E[x]+1 E [ ( x + 1 ) 3 − x 3 ] = E [ 3 x 2 + 3 x + 1 ] = 3 E [ x 2 ] + 3 E [ x ] + 1 ,由此可知我们需要多维护一个长度的平方的期望,注意不是期望长度的平方,维护方法类似,在此就不再赘述了。

代码:

#include<bits/stdc++.h>
using namespace std;
#define LL long long
#define pa pair<int,int>
const int Maxn=300010;
const int inf=2147483647;
int read()
{
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return x*f;
}
int n;
char s[Maxn];
int main()
{
    n=read();
    scanf("%s",s+1);
    double len=0,ans=0;
    for(int i=1;i<=n;i++)
    {
        if(s[i]=='o')ans+=2.0*len+1,len+=1.0;
        else if(s[i]=='x')len=0.0;
        else ans+=(2.0*len+1)*0.5,len=(len+1.0)*0.5;
    }
    printf("%.4lf",ans);
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值