C++ 中最長配對鏈


給定了一條配對鏈。每一對包含兩個整數,第一個整數總是比第二個小,對於鏈的構建也適用同樣的規則。一個配對 (x, y) 只能在配對 (p, q) 之後新增,當且僅當 q < x。

為了解決這個問題,首先要按照第一個元素的升序對給定的配對進行排序。然後,將第一對的第二個元素與下一對的第一個元素進行比較。

輸入 − 一個數字配對鏈。{(5, 24), (15, 25), (27, 40), (50, 60)}

輸出 − 給定條件下鏈的最大長度。此處長度為 3。

演算法

maxChainLength(arr, n)
each element of chain will contain two elements a and b
Input: The array of pairs, number of items in the array.
Output: Maximum length.
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

更新於: 2019 年 9 月 25 日

130 次瀏覽

開啟你的職業

透過完成課程獲得認證

開始
廣告