def rod_cutting_matrix(prices, n):
    lengths = list(prices.keys())
    m = len(lengths)

    # Print Input Price Table (Horizontal)
    print("Input Price Table:")
    print("Length:", end=" ")
    for l in lengths:
        print(f"{l:3}", end=" ")
    print()
    print("Price: ", end=" ")
    for l in lengths:
        print(f"{prices[l]:3}", end=" ")
    print("\n")

    # Create DP matrix (m+1) x (n+1)
    dp = [[0] * (n + 1) for _ in range(m + 1)]

    # Fill DP table
    for i in range(1, m + 1):
        for j in range(1, n + 1):
            if lengths[i - 1] <= j:
                dp[i][j] = max(
                    prices[lengths[i - 1]] + dp[i][j - lengths[i - 1]],
                    dp[i - 1][j]
                )
            else:
                dp[i][j] = dp[i - 1][j]

    # Print Profit Matrix
    print("Profit Matrix:")
    for row in dp:
        for val in row:
            print(f"{val:3}", end=" ")
        print()

    # Traceback to find pieces used
    res = dp[m][n]
    print(f"\nMaximum obtained value is {res}")
    j = n
    pieces = []
    i = m
    while i > 0 and j > 0:
        if dp[i][j] != dp[i - 1][j]:
            pieces.append(lengths[i - 1])
            j -= lengths[i - 1]
        else:
            i -= 1

    print("\nPieces used for maximum profit:")
    print(" ".join(map(str, pieces[::-1])))


# Example
prices = {1: 1, 2: 5, 3: 8, 4: 9, 5: 10, 6: 17, 7: 17, 8: 20}
n = 8
rod_cutting_matrix(prices, n)
