
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum of Costs of All Simple Undirected Graphs with n Nodes in Python
Suppose we have an undirected graph G with n nodes. Now consider the cost of a simple undirected graph is the sum of the costs of its nodes. And The cost of a node is D^k, where D is its degree. Now we have n and k values. We have to find the sum of the costs of all possible simple undirected graphs with n nodes. The result may be very large, so return the result modulo 1005060097.
So, if the input is like n = 3 k = 2, then the output will be 36 because, there are eight simple graphs with 3 nodes.
- One graph with only 3 edges, and its cost is 2^2+2^2+2^2 = 12.
- There graphs with two edges, and the cost of each is 1^2+1^2+2^2 = 6.
- Three graphs with one edge, and the cost of each is 0^2+1^2+1^2 = 2.
- One graph with no edges, and its cost is 0^2+0^2+0^2 = 0.
So, the total is 12*1 + 6*3 + 2*3 + 0*1 = 36.
To solve this, we will follow these steps −
- Define a function choose() . This will take n, k
- product := 1
- for i in range n to n-k, decrease by 1, do
- product := product * i
- for i in range 1 to k, do
- product := product / i
- return product as integer
- Define a function util() . This will take d, n
- return choose(n-1, d) * 2 ^(choose(n-1, 2))
- From the main method, do the following:
- total := 0
- for d in range 0 to n - 1, do
- total := total + util(d, n) * d^k
- total := total mod 1005060097
- return (total * n) mod 1005060097
Example
Let us see the following implementation to get better understanding −
def choose(n, k): product = 1 for i in range(n, n-k, -1): product *= i for i in range(1, k+1): product /= i return int(product) def util(d, n): return choose(n-1, d) * 2 ** (choose(n-1, 2)) def solve(n, k): total = 0 for d in range(n): total += util(d, n) * d ** k total %= 1005060097 return (total * n) % 1005060097 n = 3 k = 2 print(solve(n, k))
Input
3, 2
Output
36
Advertisements