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
广告