牛客5 Boxes 数学期望

题目描述

There're n boxes in front of you. You know that each box contains a ball either in white or in black. The probability for a ball to be white is 1/2, and the colors of balls are independent of each other. The PJ King invites you to guess the colors of all balls. PJ King has assigned some costs to the boxes. If we number the boxes from 1​ to n​, the cost to open the box i is wi​, and after a box is opened you can see the ball inside this box.

For sure, there's no way to know all the colors except by opening all boxes. However, Gromah wants to give you some hints. Gromah can tell you secretly the number of black balls among all boxes that have not been opened yet, but you have to pay C​ cost to get one such hint from Gromah. Anyway, if you're superpowered, you can do it without any hint. What's the mathematical expectation of the minimum cost to figure out all colors of balls?

输入描述:

The first line contains an integer n (1≤n≤10^5)n and a decimal C (0<C≤10^9), representing the number of boxes and the cost to get a hint from Gromah.

The second line contains n decimals w1,w2,⋯ ,wn (0<wi≤10^9).

All decimal numbers in the input have at most six decimal places.

输出描述:

Output one line with the expected minimum cost. Your answer will be considered to be correct if the relative or absolute error is less than 10^−6.

示例1

输入

2 0.1 1 1

输出

0.6

说明

For the first test case, you can pay 0.1 cost to get a hint from Gromah. If the number of black balls is 0 or 2​, you will know the colors in each box. This case has a probability of 1/2. Otherwise, you will know that the colors of the two balls are distinct, so you only have to open any of the boxes. Therefore, the expected cost is 0.1+1/2×1=0.6.

示例2
 

输入

4 0.123456
1 1 1 1

输出

2.248456

思路:

第一种情况是:不花c知道有多少个黑球,全部打开,那么所花就是箱子价值总和。
第二种情况是:将 wi 从小到大排序,先花c知道有多少个黑球,再剩下的就相当于一个随机 01 序列,
那么每次打开一个球,结束的概率为(1/2)^(n-i).所以如果从前往后遍历的话,
代价就为:C + Σ wi*(1-(1/2)^(n-i)). 
两者取较小值即可。

代码如下:

#include <bits/stdc++.h>
using namespace std;
#define N 1000005
int n;
double c,w[N],ans,f=1;
int main(){
	cin>>n>>c;
	for(int i=1;i<=n;i++){
		cin>>w[i];
		ans+=w[i];
	}
	sort(w+1,w+n+1);//从小到大排序 
    for(int i=n;i>=1;i--){
    	c+=w[i]*(1-f);
    	f/=2;
	}
	printf("%.8lf",min(ans,c));
	return 0;
	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值