C - NetworkConfiguration
Time limit : 2sec / Memory limit : 256MB
Score : 100 points
Problem Statement
There are N servers on thenetwork in your office. Each server can only communicate with the other N − 1 servers.
You are given M forbidden pairs (a ,b)(1 ≤ i ≤ M) of servers. Each of them means that direct communication betweenserver a and b is forbidden.
You will configure the network underthese constraints. More specifically, for every pair of two different servers,you will determine whether they will directly communicate each other. Twoconfigurations of network is considered different if there exist two servers thatdirectly communicate in one of the two configuration, and do not directly communicatein the other.
Under these conditions, you need toconfigure the network so that every servers can communicate with all otherservers. How many different such configurations there are?
Constraints
2 ≤ N ≤ 6
0 ≤ M ≤ N(N − 1) ⁄2
1 ≤ a < b ≤ N
(a ,b ) ≠ (a ,b )(1 ≤ i < j ≤ M)
Input
Input is given from Standard Input in the following format:
Output
Print how many different configurations are possible.
Sample Input 1
4 2
1 2
3 4
Sample Output 1
5
The following five configurations are possible:
There is direct communication between server 1 and 3, between 1 and 4 and
between 2 and 3.
There is direct communication between server 1 and 3, between 1 and 4 and
between 2 and 4.
There is direct communication between server 1 and 3, between 2 and 3 and
between 2 and 4.
There is direct communication between server 1 and 4, between 2 and 3 and
between 2 and 4.
There is direct communication between server 1 and 3, between 1 and 4, between 2
and 3 and between 2 and 4.
Sample Input 2
5 0
Sample Output 2
728
Sample Input 3
6 2
1 2
3 4
Sample Output 3
5758
AC代码(Python):组合+并查集,求解连通子图的个数
#coding=utf-8
result = 0
def problem3():
(N, M) = (int(x) for x in raw_input().split())
#先构造出所有的边
#edges = []
from itertools import combinations
edges = list(combinations(range(1,N+1), 2))
for _ in range(M):#M行2列
curPair = tuple(int(x) for x in raw_input().split())
if curPair in edges:
edges.remove(curPair)
#最多有N*(N-1)/2-M条边,最少有N-1条边
for eNums in range(N*(N-1)/2-M, N-1-1, -1):
tmp = list(combinations(edges, eNums))#选出eNums条边
for i in range(len(tmp)):
judge(tmp[i], N, eNums)
global result
print result
def judge(tmp1, N, M):
map = [0]*100
def find(i):
if map[i]==i:
return i
else:
return find(map[i])
for i in range(N):
map[i]=i
for i in range(M):
(a, b) = tmp1[i]
map[find(a-1)]=map[find(b-1)]
cnt = 0
for i in range(N):
if map[i]==i:
cnt += 1
global result
if cnt==1:
result += 1
problem3()