Advertisement
whiteshark05

Hotel Construction

Jun 1st, 2023 (edited)
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.34 KB | Software | 0 0
  1. import sys, bisect, collections, heapq, functools
  2. input = sys.stdin.readline
  3. from math import factorial as fact
  4.  
  5. rs = lambda: input().strip()
  6. ri = lambda: int(input())
  7. rmi = lambda: map(int, input().split())
  8. ra = lambda: [int(x) for x in input().split()]
  9.  
  10. INF = 10**18
  11. MOD = 10**9 + 7
  12.  
  13. def nCr(n,r):
  14.     return fact(n)//(fact(n-r) * fact(r))
  15.    
  16. def solve():
  17.     dist = [[INF] * n for _ in range(n)]
  18.     for u, v in A:
  19.         u -= 1
  20.         v -= 1
  21.         dist[u][v] = 1
  22.         dist[v][u] = 1
  23.  
  24.     #Floyd-Warshall DP to calculate dist between any node i and j
  25.     for k in range(n):
  26.         for i in range(n):
  27.             for j in range(n):
  28.                 dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
  29.  
  30.     #Store frequency of all possible distances between any pair i, j (i != j)
  31.     freq = collections.Counter()
  32.     for i in range(n):
  33.         for j in range(i + 1, n):
  34.             if dist[i][j] == INF: continue #No connection, skip
  35.             freq[dist[i][j]] += 1
  36.            
  37.     #If there are v pairs per distance (v >= 3), we can add v choose 3 into final answer
  38.     ans = 0
  39.     for v in freq.values():
  40.         if v >= 3:
  41.             ans += nCr(v,3)
  42.     return ans
  43.    
  44. test_case = 1
  45. for _ in range(test_case):
  46.     n = 5
  47.     A =  [[1, 2], [1, 3], [1, 4], [1, 5]]
  48.     print(solve())
  49.        
  50.        
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement