Program to find number of sets of k-non-overlapping line segments in Python

PythonServer Side ProgrammingProgramming

Suppose we have n points on a line, where the ith point (from 0 to n-1) is at position x = i, we have to find the number of ways we can draw exactly k different non-overlapping line segments such that each segment covers two or more points. The endpoints of each line segment must have integral coordinates. The k line segments do not have to cover all given n points, and they can share endpoints. If the answer is too large, then return result mod 10^9+7.

So, if the input is like n = 4 k = 2, then the output will be 5 because we can make five possibilities [(0 to 2),(2 to 3)], [(0 to 1),(1 to 3)], [(0 to 1),(2 to 3)], [(1 to 2),(2 to 3)] and [(0 to 1),(1 to 2)]

To solve this, we will follow these steps −

  • m := 10^9 + 7
  • n := n - 1
  • Define a function dp() . This will take i, covered, j
  • if i is same as n, then
    • return true if j is same as k otherwise false
  • if j > k, then
  • ans := dp(i + 1, False, j) + dp(i + 1, True, j + 1)
  • if covered is true, then
    • ans := ans + dp(i + 1, True, j)
  • return ans mod m
  • From the main method return dp(0, False, 0)

Example

Let us see the following implementation to get better understanding −

def solve(n, k):
   m = 10 ** 9 + 7
   n -= 1

   def dp(i, covered, j):
      if i == n:
         return j == k
      if j > k:
         return 0
      ans = dp(i + 1, False, j) + dp(i + 1, True, j + 1)
      if covered:
         ans += dp(i + 1, True, j)
      return ans % m

   return dp(0, False, 0)

n = 4
k = 2
print(solve(n, k))

Input

4, 2

Output

5
raja
Published on 05-Oct-2021 11:16:36
Advertisements