Hdu 1423 Greatest Common Increasing Subsequence

最长公共上升子序列,关于O(n^2)的算法,这篇文章讲的不错。

http://ishare.iask.sina.com.cn/f/14329392.html?from=like

#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <string>
#include <algorithm>
using namespace std;

const int MAXN = 1005;

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

int n, m;

void init()
{
	memset(f, 0, sizeof(f));
}

void read_case()
{
	scanf("%d", &n);
	for(int i = 1; i <= n; i++) scanf("%d", &a[i]);
	scanf("%d", &m);
	for(int i = 1; i <= m; i++) scanf("%d", &b[i]);
}

void dp()
{
	init();
	for(int i = 1;i <= n;i++)
	{
		int MAX = 0;
		for(int j = 1; j <= m; j++)
		{
			if (a[i] > b[j]) MAX = max(MAX, f[j]);
			if (a[i] == b[j]) f[j] = MAX+1;		
		}
	}
	int ans = 0;
	for(int i = 1; i <= m; i++) ans = max(ans, f[i]);
	printf("%d\n", ans);
}

void solve()
{
	read_case();
	dp();
}

int main()
{
	int T;
	scanf("%d", &T);
	while(T--)
	{
		solve();
		if(T) printf("\n");
	}
	return 0;
}


你可能感兴趣的:(Hdu 1423 Greatest Common Increasing Subsequence)