对的链的最大长度


给定一对链条。在每对链条中,有两个整数,第一个整数总比第二个整数小,这一规则也适用于链条构造。只有当 q < x 时,才能在对 (p, q) 之后添加对 (x, y)。

要解决此问题,我们首先必须按第一个元素的递增顺序对给定的对进行排序。之后,我们将一对的第二个元素与下一对的第一个元素进行比较。

输入和输出

Input:
A chain of number pairs. {(5, 24), (15, 25), (27, 40), (50, 60)}
Output:
Largest length of the chain as given criteria. Here the length is 3.

算法

maxChainLength(arr, n)

链条的每个元素都将包含两个元素 a 和 b

输入 −  对的数组、数组中的项目数。

输出 − 最大长度。

Begin
   define maxChainLen array of size n, and fill with 1
   max := 0

   for i := 1 to n, do
      for j := 0 to i-1, do
         if arr[i].a > arr[j].b and maxChainLen[i] < maxChainLen[j] + 1
            maxChainLen[i] := maxChainLen[j] + 1
      done
   done

   max := maximum length in maxChainLen array
   return max
End

示例

#include<iostream>
#include<algorithm>
using namespace std;

struct numPair {    //define pair as structure
   int a;
   int b;
};

int maxChainLength(numPair arr[], int n) {
   int max = 0;
   int *maxChainLen = new int[n];    //create array of size n

   for (int i = 0; i < n; i++ )    //Initialize Max Chain length values for all indexes
      maxChainLen[i] = 1;

   for (int i = 1; i < n; i++ )
      for (int j = 0; j < i; j++ )
         if ( arr[i].a > arr[j].b && maxChainLen[i] < maxChainLen[j] + 1)

            maxChainLen[i] = maxChainLen[j] + 1;

   // maxChainLen[i] now holds the max chain length ending with pair i

   for (int i = 0; i < n; i++ )
      if ( max < maxChainLen[i] )
         max = maxChainLen[i];    //find maximum among all chain length values
   delete[] maxChainLen;    //deallocate memory
   return max;
}

int main() {
   struct numPair arr[] = {{5, 24},{15, 25},{27, 40},{50, 60}};
   int n = 4;
   cout << "Length of maximum size chain is " << maxChainLength(arr, n);
}

输出

Length of maximum size chain is 3

更新于: 2020-06-17

505 次查看

开启你的 事业

完成此课程获取认证

开始
广告
© . All rights reserved.