對的鏈的最大長度


給定一對鏈條。在每對鏈條中,有兩個整數,第一個整數總比第二個整數小,這一規則也適用於鏈條構造。只有當 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 次檢視

開啟你的 事業

完成此課程獲取認證

開始
廣告