Program to find out how many transfer requests can be satisfied in Python

PythonServer Side ProgrammingProgramming

Suppose, there are n number of hostel rooms numbered from 0 to n-1. The students in the hostel rooms want to transfer to another room, and they place several requests to do that. No hostel seat remains vacant, a transfer request is only taken care of if another student takes the place of the student willing to transfer. So, given the requests, we have to find out how many requests can be satisfied.

So, if the input is like n = 3, requests = [[0,2],[1,0],[2,1]], then the output will be 3.

The student in room 0 transfers to room 2.

The student in room 1 transfers to room 0.

The student in room 2 transfers to room 1.

To solve this, we will follow these steps −

  • for k in range size of requests to -1, decrease by 1, do

    • for c in all combinations of (0 to size of requests and k), do

      • d := a new array of size n containing value 0

      • for each i in c, do

        • d[requests[i, 0]] := d[requests[i, 0]] - 1

        • d[requests[i, 1]] := d[requests[i, 1]] + 1

      • if none of the items in d are true, then

        • return k

  • return 0

Example

Let us see the following implementation to get better understanding

from itertools import combinations
def solve(n, requests):
   for k in range(len(requests), 0, -1):
      for c in combinations(range(len(requests)), k):
         d = [0] * n
         for i in c:
            d[requests[i][0]] -= 1
            d[requests[i][1]] += 1
         if not any(d):
            return k
   return 0

print(solve(3, [[0,2],[1,0],[2,1]]))

Input

3, [[0,2],[1,0],[2,1]]

Output

3
raja
Updated on 07-Oct-2021 07:13:27

Advertisements