最長對鏈


有一個對鏈。每個對都有兩個整數,第一個整數總是較小的那個,第二個整數則是較大的那個,鏈的構建也如此。僅當 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

更新日期: 17-Jun-2020

505 已檢視

開啟你的 職業之旅

完成課程獲得認證

開始
廣告
© . All rights reserved.