51Nod-1632-B君的连通

51Nod-1632-B君的连通

B国拥有n个城市,其交通系统呈树状结构,即任意两个城市存在且仅存在一条交通线将其连接。A国是B国的敌国企图秘密发射导弹打击B国的交通线,现假设每条交通线都有50%的概率被炸毁,B国希望知道在被炸毁之后,剩下联通块的个数的期望是多少?

Input
一个数n(2<=n<=100000)
接下来n-1行,每行两个数x,y表示一条交通线。(1<=x,y<=n)
数据保证其交通系统构成一棵树。
Output
一行一个数,表示答案乘2^(n-1)后对1,000,000,007取模后的值。
Input示例
3
1 2
1 3
Output示例
8

题解: 

1, 因为数据保证是一棵树,所以每次去掉一条边,则增加一个connected component。 

2, 对于n节点的树,一共有n-1 条边,每一条边有50%的可能被去掉,则期望留下 (n-1)/2 条边。 此时有 (n+1)/2 个 connected component。 

最后的结果是:  ans = (n+1)/2 * 2^(n-1) = (n+1)*2^(n-2)

#include <cstdio> 
const int MOD = 1000000007; 

int main(){
	int n, x, y; 
	scanf("%d", &n); 
	for(int i=0; i<n-1; ++i){
		scanf("%d %d", &x, &y); 
	}
	long long ans = n + 1;
	for(int i=1; i<=n-2; ++i){
		ans = ans*2; 
		ans = ans % MOD; 
	}
	printf("%lld
", ans );
	return 0; 
}
原文地址:https://www.cnblogs.com/zhang-yd/p/6389552.html