📜  打印成对的最大长度链

📅  最后修改于: 2021-05-07 05:18:54             🧑  作者: Mango

您会得到n对数字。在每对中,第一个数字始终小于第二个数字。如果b

例子:

Input:  (5, 24), (39, 60), (15, 28), (27, 40), (50, 90)
Output: (5, 24), (27, 40), (50, 90)

Input:  (11, 20), {10, 40), (45, 60), (39, 40)
Output: (11, 20), (39, 40), (45, 60) 

在上一篇文章中,我们讨论了关于最大长度成对链的问题。但是,该帖子仅涉及与找到最大大小链的长度有关的代码,但与最大大小链的构造无关。在这篇文章中,我们将讨论如何构造对的最大长度链。

想法是首先按照给定的对的第一个元素的升序对它们进行排序。令arr [0..n-1]为排序后的输入对数组。我们定义向量L,使得L [i]本身就是一个向量,该向量存储以arr [i]结尾的arr [0..i]对的最大长度链。因此,对于索引i,L [i]可以递归写为–

L[0] = {arr[0]}
L[i] = {Max(L[j])} + arr[i] where j < i and arr[j].b < arr[i].a 
     = arr[i], if there is no such j

例如,对于(5,24),(39、60),(15、28),(27、40),(50、90)

L[0]: (5, 24)
L[1]: (5, 24) (39, 60)
L[2]: (15, 28)
L[3]: (5, 24) (27, 40)
L[4]: (5, 24) (27, 40) (50, 90)

请注意,对的排序已完成,因为我们需要找到最大的对长度,此处的排序无关紧要。如果我们不排序,我们将获得升序排列的对,但它们将不是最大可能的对。

以下是上述想法的实现–

C++
/* Dynamic Programming solution to construct
   Maximum Length Chain of Pairs */
#include 
using namespace std;
  
struct Pair
{
    int a;
    int b;
};
  
// comparator function for sort function
int compare(Pair x, Pair y)
{
    return x.a < y.a;
}
  
// Function to construct Maximum Length Chain
// of Pairs
void maxChainLength(vector arr)
{
    // Sort by start time
    sort(arr.begin(), arr.end(), compare);
  
    // L[i] stores maximum length of chain of
    // arr[0..i] that ends with arr[i].
    vector > L(arr.size());
  
    // L[0] is equal to arr[0]
    L[0].push_back(arr[0]);
  
    // start from index 1
    for (int i = 1; i < arr.size(); i++)
    {
        // for every j less than i
        for (int j = 0; j < i; j++)
        {
            // L[i] = {Max(L[j])} + arr[i]
            // where j < i and arr[j].b < arr[i].a
            if ((arr[j].b < arr[i].a) &&
                (L[j].size() > L[i].size()))
                L[i] = L[j];
        }
        L[i].push_back(arr[i]);
    }
  
    // print max length vector
    vector maxChain;
    for (vector x : L)
        if (x.size() > maxChain.size())
            maxChain = x;
  
    for (Pair pair : maxChain)
        cout << "(" << pair.a << ", "
             << pair.b << ") ";
}
  
// Driver Function
int main()
{
    Pair a[] = {{5, 29}, {39, 40}, {15, 28},
                {27, 40}, {50, 90}};
    int n = sizeof(a)/sizeof(a[0]);
  
    vector arr(a, a + n);
  
    maxChainLength(arr);
  
    return 0;
}


Python3
# Dynamic Programming solution to construct
# Maximum Length Chain of Pairs
class Pair:
  
    def __init__(self, a, b):
        self.a = a
        self.b = b
  
    def __lt__(self, other):
        return self.a < other.a
  
def maxChainLength(arr):
      
    # Function to construct
    # Maximum Length Chain of Pairs 
  
    # Sort by start time
    arr.sort()
  
    # L[i] stores maximum length of chain of
    # arr[0..i] that ends with arr[i].
    L = [[] for x in range(len(arr))]
  
    # L[0] is equal to arr[0]
    L[0].append(arr[0])
  
    # start from index 1
    for i in range(1, len(arr)):
  
        # for every j less than i
        for j in range(i):
  
            # L[i] = {Max(L[j])} + arr[i]
            # where j < i and arr[j].b < arr[i].a
            if (arr[j].b < arr[i].a and 
                len(L[j]) > len(L[i])):
                L[i] = L[j]
  
        L[i].append(arr[i])
  
    # print max length vector
    maxChain = []
    for x in L:
        if len(x) > len(maxChain):
            maxChain = x
  
    for pair in maxChain:
        print("({a},{b})".format(a = pair.a, 
                                 b = pair.b), 
                                 end = " ")
    print()
  
# Driver Code
if __name__ == "__main__":
    arr = [Pair(5, 29), Pair(39, 40), 
           Pair(15, 28), Pair(27, 40),
           Pair(50, 90)]
    n = len(arr)
    maxChainLength(arr)
  
# This code is contributed 
# by vibhu4agarwal


输出:

(5, 29) (39, 40) (50, 90)

上述动态编程解决方案的时间复杂度为O(n 2 ),其中n是对的数量。
该程序使用的辅助空间为O(n 2 )。