这两个题的套路是一样的,放在一起说。
3450:
因为期望有线性性质,也就是说我们可以分开算每一位的期望,再加起来就是答案。由于 E[(x+1)2−x2]=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)3−x3]=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);
}