Geeks 面试题 - Maximum Length Chain of Pairs
2014-03-08 07:42
399 查看
Dynamic Programming | Set 20 (Maximum Length Chain of Pairs)
You are given n pairs of numbers. In every pair, the first number is always smaller than the second number.A pair (c, d) can follow another pair (a, b) if b < c. Chain of pairs can be formed in this fashion. Find the longestchain which can be formed from a given set of pairs.
Source: Amazon Interview | Set 2
For example, if the given pairs are {{5, 24}, {39, 60}, {15, 28}, {27, 40}, {50, 90} }, then the longest chain that can be formed is of length 3, and the chain is {{5, 24}, {27, 40}, {50, 90}}
This problem is a variation of standard Longest Increasing Subsequence problem. Following is a simple two step process.
1) Sort given pairs in increasing order of first (or smaller) element.
2) Now run a modified LIS process where we compare the second element of already finalized LIS with the first element of new LIS being constructed.
http://www.geeksforgeeks.org/dynamic-programming-set-20-maximum-length-chain-of-pairs/
本博客贴出动态规划法解和贪心法的程序。
动态规划法的时间效率是O(n*n);
而贪心法的效率是O(nlgn),主要是因为sort需要O(nlgn)的时间效率,而贪心法本身只需要O(n).
// Structure for a pair struct pairChain { int a; int b; }; // This function assumes that arr[] is sorted in increasing order // according the first (or smaller) values in pairs. int maxChainLengthDP( struct pairChain arr[], int n) { if (n < 2) return n; int *A = new int ; A[0] = 1; int max_len = 0; for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { A[i] = 1; if (arr[i].a > arr[j].b) A[i] = A[i] < A[j]+1? A[j]+1:A[i]; max_len = max_len < A[i]? A[i]:max_len; } } return max_len; } bool operator<(pairChain p1, pairChain p2) { return p1.b < p2.b; } #include<algorithm> int maxChainLengthGreedy( struct pairChain arr[], int n) { if (n < 2) return n; std::sort(arr, arr+n); int max_len = 1; int active_p = 0; for (int i = 1; i < n; i++) { if (arr[i].a > arr[active_p].b) { max_len++; active_p = i; } } return max_len; };
相关文章推荐
- DP20 求pair的最大长度链 Maximum Length Chain of Pairs @geeksforgeeks
- Dynamic Programming | Set 20 (Maximum Length Chain of Pairs)
- 算法练习(34):Maximum Length of Pair Chain
- LeetCode 646 Maximum Length of Pair Chain(贪心)
- Maximum Length of Pair Chain
- Maximum Length of Pair Chain问题及解法
- LeetCode:Maximum Length of Pair Chain
- LeetCode - 646 - Maximum Length of Pair Chain
- Maximum Length of Pair Chain【双链的最大长度】
- LeetCode 646 Maximum Length of Pair Chain (贪心)
- LeetCode#646 Add Maximum Length of Pair Chain题解(C++版)
- LeetCode Maximum Length of Pair Chain
- [LeetCode] Maximum Length of Pair Chain 链对的最大长度
- 第15周Maximum Length of Pair Chain
- LeetCode - Maximum Length Of Pair Chain(算法)
- Maximum_Length_of_Pair_Chain
- Leetcode 718 Maximum Length of Repeated Subarray
- 算法题目--Maximum Length of Repeated Subarray
- [LeetCode] DP 之 Maximum Length of Repeated Substring
- 718[Medium]:Maximum Length of Repeated Subarray