【最长公共子序列】杭电 HDU 1423 Greatest Common Increasing Subsequence

阅读更多

 

 

/* THE PROGRAM IS MADE BY PYY */
/*----------------------------------------------------------------------------//
    Copyright (c) 2012 panyanyany All rights reserved.

    URL   : http://acm.hdu.edu.cn/showproblem.php?pid=1423
    Name  : 1423 Greatest Common Increasing Subsequence
    Classification : 最长公共子序列

    Date  : Wednesday, July 11, 2012
    Time Stage : two hour

    Result:
6178365	2012-07-11 11:46:23	Accepted	1423
15MS	236K	1670 B
C++	pyy


Test Data :

Review :
参考了大牛的代码:
http://blog.csdn.net/q3498233/article/details/5398888#html
//----------------------------------------------------------------------------*/

#include 
#include 
#include 
#include 
#include 

#include 
#include 
#include 
#include 
#include 

using namespace std ;

#define MEM(a, v)        memset (a, v, sizeof (a))    // a for address, v for value
#define max(x, y)        ((x) > (y) ? (x) : (y))
#define min(x, y)        ((x) < (y) ? (x) : (y))

#define INF     (0x3f3f3f3f)
#define MAXN	(1005)

#define L(x)	((x)<<1)
#define R(x)	(((x)<<1)|1)
#define M(x, y)	(((x)+(y)) >> 1)

#define DB    //

int a[MAXN], b[MAXN], dp[MAXN];

int GCIS(int n1, int n2)
{
	int i, j, pos;
	MEM(dp, 0);
	for (i = 1; i <= n1; ++i)
	{
		pos = 0;
		for (j = 1; j <= n2; ++j)
		{
			// 遍历b的同时,找出 j 之前最大的公共子序列所在点 pos,并且要使 b[pos] < a[i]
			// 这样,当下一句 b[j]==a[i] 时,就可以直接得到 j 点的最大公共子序列了:dp[pos]+1
			// 像 dp[j-1]+1,或者 dp[j]+1 之类的,都不能保证结果最优。
			if (b[j] < a[i] && dp[pos] < dp[j])
			{
				pos = j;
			}

			if (b[j] == a[i])
				dp[j] = dp[pos] + 1;
		}
	}
	j = 0;
	for (i = 1; i <= n2; ++i)
		j = max(j, dp[i]);

	return j;
}

int main()
{
	int i, n1, n2, tc;
	while (scanf("%d", &tc) != EOF)
	{
		while (tc--)
		{
			scanf("%d", &n1);
			for (i = 1; i <= n1; ++i)
				scanf("%d", a+i);
			scanf("%d", &n2);
			for (i = 1; i <= n2; ++i)
				scanf("%d", b+i);

			printf("%d\n", GCIS(n1, n2));
			if (tc)
				putchar('\n');
		}
	}
	return 0;
}

你可能感兴趣的:(最长公共子序列,杭电,HDU,GCIS)