쌍의 사슬이 주어집니다. 각 쌍에는 두 개의 정수가 있으며 첫 번째 정수는 항상 작고 두 번째 정수가 크면 체인 구성에도 동일한 규칙을 적용할 수 있습니다. q
이 문제를 해결하려면 먼저 주어진 쌍을 첫 번째 요소의 오름차순으로 정렬해야 합니다. 그런 다음 쌍의 두 번째 요소를 다음 쌍의 첫 번째 요소와 비교합니다.
입력 및 출력
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)
체인의 각 요소에는 두 개의 요소와 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