您的位置:首页 > 职场人生

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 longest
chain 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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: