有一对成对的链。在每对中,有两个整数,第一个整数始终较小,而第二个整数较大,同样的规则也可应用于链构建。仅当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]现在拥有以对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