杭电 bestcoder round#7 1002 Little Pony and Alohomora Part I

来源:互联网 发布:北京seo服务 编辑:程序博客网 时间:2024/05/18 01:57

Problem DescriptionTrixie 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. InputInput contains multiple test cases (less than 100). For each test case, only one line contains one integer n (1≤n≤1000000000). OutputFor each case, output the corresponding result, rounded to 4 digits after the decimal point. Sample Input12 Sample Output1.00001.5000HintThe 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)

理解题意:假设已经知道f(n)的值,求f(n+1)的值,第n+1个盒子用万能钥匙打开,如果里面的钥匙是第n+1个(自己)的钥匙,那么使用万能钥匙的次数就是f(n)+1;

else 如果是其他n个盒子的钥匙,使用万能钥匙的次数就是f(n);共n中情况;so f(n+1)=(f(n)+1+f(n)*n)/(n+1)=f(n)+1/(n+1);f(1)=1;so f(n)=1+1/2+...+1/n;

要知道n<=1000000000;暴力是不可取的,但本人用暴力验证了推理。。。有一个欧拉常数c=0.57721566;f(n)大致会等于log(n)+c;(当n比较大时);小于100000的可以暴力;




 代码如下:#include#include#include#include#include#include#include#include#include#include#include#define c 0.57721566using namespace std;

int main(){int n;while(~scanf("%d",&n)){double ans=0;if(n>100000)for(int i=1;i<=n;i++){ans+=1.0/i;}elseans=log(n)+c;printf("%.4lf\n",ans);} return 0;}

0 0
原创粉丝点击