C ++中的最大对长度链
有一对成对的链。在每对中,有两个整数,第一个整数始终较小,而第二个整数较大,同样的规则也可用于链构建。仅当q<x时,才可以在对(p,q)之后添加对(x,y)。
为了解决这个问题,首先我们必须按照给定的对按照第一个元素的升序进行排序。之后,我们将比较一对的第二个元素和下一对的第一个元素。
输入-一串数字对。{(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]现在拥有以对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