在OpenJudge看到一个题目(#4109),题目描述如下:
小明和小红去参加party。会场中总共有n个人,这些人中有的是朋友关系,有的则相互不认识。朋友关系是相互的,即如果A是B的朋友,那么B也是A的朋友。小明和小红想知道其中某两个人有多少个公共的朋友。
输入第一行为一个正整数c,代表测试数据的个数。接下来是c组测试数据。
对于每组测试数据,第一行是三个数字n(2<=n<=100),m和k,分别表示会场中的人数,已知的朋友关系数目,问题的数目。接下来的m行,每行用两个数字i和j(1<=i,j<=n)表示了一个朋友关系,表示第i个人和第j个人是朋友关系。接下来的k行,每行用两个数字i和j(1<=i,j<=n)表示一个问题,请问第i个人和第j个人有多少公共的朋友。输出对于第i组测试数据,首先输出一行”Case i:”,接下来得k行代表了k个问题,每行输出第i个人和第j个人有多少公共的朋友。
用Python写了段代码,大致实现:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
1 # -*- coding:utf-8 -*- 2 3 def set_1(i, q): 4 ''' generate a i*i ARRAY for all relationships 5 if there is a relation set 1 or 0 6 return i*i ARRAY with 1 or 0 7 ''' 8 a = [0 for i in range(i*i)] 9 for j in range(len(q)): 10 n, m = q[j] 11 a[(n-1)*i+(m-1)] = 1 12 a[(m-1)*i+(n-1)] = 1 13 return a 14 15 def solve(i, q, r): 16 ''' solve question 17 i is the number of people 18 q is the set of questions 19 r is the set of relationships, the result of function set_1(); 20 ''' 21 result = 0 22 for j in range(len(r)): 23 n, m = r[j] 24 for l in range(i): 25 if q[(n-1)*i+l] == 1 and q[(m-1)*i+l] == 1: 26 result += 1 27 print(result) 28 result = 0 29 30 def main(): 31 d = [ 3, [3,2,2], 32 [1,3], 33 [2,3], 34 [1,2], 35 [1,3], 36 [4,3,2], 37 [1,2], 38 [2,3], 39 [1,4], 40 [2,4], 41 [1,3], 42 [5,2,1], 43 [1,2], 44 [1,4], 45 [3,4] 46 ] 47 for x in d: #Dispaly input 48 print(x) 49 50 loc = [] 51 for m in range(1,len(d)): #Get the index of every question 52 if len(d[m])==3: 53 loc.append(m) 54 55 for i in range(len(loc)): #Sovle each question 56 pNum, qNum, aNum = d[loc[i]] #slice out R and Q in d[] 57 t = loc[i]+1 58 R = d[t:t+qNum] 59 Q = d[t+qNum:t+qNum+aNum] 60 61 r_1 = set_1(pNum,R) # set 1 for question 62 print('-------------------\nCase'+str(i+1)+':') 63 solve(pNum, r_1, Q) 64 if __name__=='__main__': 65 main() 66 67 '''OUTPUT 68 3 69 [3, 2, 2] 70 [1, 3] 71 [2, 3] 72 [1, 2] 73 [1, 3] 74 [4, 3, 2] 75 [1, 2] 76 [2, 3] 77 [1, 4] 78 [2, 4] 79 [1, 3] 80 [5, 2, 1] 81 [1, 2] 82 [1, 4]