hdoj4986Little Pony and Alohomora Part I【概率dp】

本题描述了一个关于小马Trixie使用魔法解锁一系列盒子的问题,并提供了一段C++代码实现。通过数学方法求解期望值,旨在找到打开所有盒子所需的最小魔法次数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Little Pony and Alohomora Part I

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 396    Accepted Submission(s): 207


Problem Description
Trixie is a female unicorn pony and traveling magician, having been rumored to be "the most magical unicorn in all of Equestria". One day, Trixie arrives in Ponyville.


There is n boxes on the stage. There is a random key in each box and each box has a key match it. As a unicorn, Trixie can use "Alohomora"(the unlocking spell) to open any box. 

Trixie would like to open all the boxes, also Trixie would like to minimize the spells she used. Help Trixie to calculate the expected number of spells she need to used in order to open all the boxes necessary.
 

Input
Input contains multiple test cases (less than 100). 
For each test case, only one line contains one integer n (1<=n<=1000000000).
 

Output
For each case, output the corresponding result, rounded to 4 digits after the decimal point.
 

Sample Input
1 2
 

Sample Output
1.0000 1.5000
Hint
The second sample: There are two different permutations when n equal to 2: (1, 2) and (2, 1). Trixie need to use 2 spells in (1, 2) and 1 spell in (2, 1).
 

设:E[i]为i个盒子的期望则有再增加一个盒子有两种情况钥匙在该盒子内此时期望为E[i+1]=E[i]+1;第二种情况钥匙不在该盒子内则有E[i+1]=E[i]考虑第一种情况的发生概率为1/(i+1)第二种情况发生的概率为i/(I+1)所以有E[i]=E[i-1]+1/i;E[1]=1;即求调和数列的前n项和;

#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
#include<list>
#include<cmath>
#include<vector>
#define euler 0.57721566490153286060651209
using namespace std;
const int maxn=2000010;
double E[maxn];
void init(){
    for(int i=1;i<maxn;++i){
        E[i]=E[i-1]+1.0/i;
    }
}
int main()
{
    init();
    int n;
    while(scanf("%d",&n)!=EOF){
        if(n<maxn){
            printf("%.4lf\n",E[n]);
        }
        else {
            printf("%.4lf\n",log(n)+euler);
        }
    }
    return 0;
} 


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值