51Nod

51Nod  - 1639 绑鞋带

 
有n根鞋带混在一起,现在重复n次以下操作:随机抽出两个鞋带头,把它们绑在一起。可以想象,这n次之后將不再有单独的鞋带头,n条鞋带系成了一些环。那么有多大概率刚好所有这些鞋带只形成了一个环?
Input
仅一行,包含一个整数n  (2<=n<=1000)。
Output
输出一行,为刚好成环的概率。
Input示例
2
Output示例
0.666667

题解: 

  参考1: https://www.51nod.com/question/index.html#!questionId=1415

  参考2: http://www.cnblogs.com/geek1116/p/6282878.html 

  看上去是很复杂的题目。 但是使用递推的方法就简单多了。 

  对于 f[i-1] 来说, f[i] 的成功情况是, 抓住一个鞋带透, 只要剩下的 2*i - 1 中有 2*i 能组成一个环, 则这个头连接上不取的那个,就可以成功匹配。

#include <iostream> 
#include <cstdio> 
#include <cstdlib> 
#include <cstring> 
using namespace std;  

int main(){
	freopen("in.txt", "r", stdin); 

	double ans; 
	int n, cnt; 
	while(scanf("%d", &n) != EOF){
		ans = 1.0; 
		cnt = 2; 
		for(int i=1; i<n; ++i){
			ans = ans*( cnt*1.0 / (cnt + 1) ); 
			cnt = cnt + 2; 
		}
		printf("%.6f
", ans ); 
	}
	return 0; 
}

  

原文地址:https://www.cnblogs.com/zhang-yd/p/6818840.html