Connected Graph POJ - 1737

An undirected graph is a set V of vertices and a set of E∈{V*V} edges.An undirected graph is connected if and only if for every pair (u,v) of vertices,u is reachable from v.
You are to write a program that tries to calculate the number of different connected undirected graph with n vertices.
For example,there are 4 different connected undirected graphs with 3 vertices.

 

Input

The input contains several test cases. Each test case contains an integer n, denoting the number of vertices. You may assume that 1<=n<=50. The last test case is followed by one zero.

Output

For each test case output the answer on a single line.

Sample Input

1
2
3
4
0

Sample Output

1
1
4
38
import java.math.*;
import java.util.*;

public class Main {
	/*组合数
	 *我们考虑分类的情况,也就是考虑1所在的点
	 *1所在的联通块大小 可能是 (1,2,...n-1) 因为要算不联通的情况
	 *所以在看当1所在的联通快的大小是i的时候,也就是说 另外(i-1)个数有 C(n-1,i-1)中情况,同时 剩下的n-i个点有 2^(完全图边数)中情况 
	 *然后就是加起来了
	 */
	public static void main(String []args) {
		    BigInteger [] []C=new BigInteger[51][51];
			for(int i=0;i<51;i++) {
				C[i][0]=C[i][i]=BigInteger.ONE;
				for(int j=1;j<i;j++) {
					C[i][j]=C[i-1][j].add(C[i-1][j-1]);
				}
			}
			
			BigInteger []f=new BigInteger[51];
			BigInteger []h=new BigInteger[51];
			
			BigInteger two=BigInteger.valueOf(2);
			for(int i=1;i<51;i++) h[i]=two.pow(i*(i-1)/2);//BigInteger的pow函数

			BigInteger G;
			for(int i=1;i<51;i++) {
				G=BigInteger.ZERO;
				for(int j=1;j<i;j++) G=G.add(C[i-1][j-1].multiply(f[j]).multiply(h[i-j]));
				f[i]=h[i].subtract(G);
			}		
			
			Scanner in=new Scanner(System.in);
			while(in.hasNext()) {
				int n=in.nextInt();
				if(n==0)break;
				System.out.println(f[n]);
			}
	}
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值