最长对链
有一个对链。每个对都有两个整数,第一个整数总是较小的那个,第二个整数则是较大的那个,链的构建也如此。仅当 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] 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
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP