Topic Link: Click to enter
Just see this topic also thought hit water problem, the result wrote an O (n^2) code to turn over time, only to find that N is 250*250 so big. On the internet, we find a way to nlgn the longest ascending subsequence, It's over. The main idea of this NLGN algorithm is to convert the longest common subsequence into the longest ascending subsequence, and then solve it with the algorithm of the longest ascending subsequence nlgn. More specific explanations can be seen in this blog post: Longest common subsequence (NLOGN)
The code is as follows:
#include <iostream>#include <cstring>#include <cstdio>#include <algorithm>using namespace STD;int Constmaxn=252*252;inta[maxn],b[maxn],c[maxn*Ten];intDP[MAXN],D[MAXN];intMain () {//freopen ("In.txt", "R", stdin); intT,case=0;intN,K1,K2;scanf("%d", &t); while(t--) {scanf("%d%d%d", &N,&K1,&K2); ++K1; ++K2;memset(DP,0,sizeof(DP)); for(intI=1; i<=k1;i++)scanf("%d", &a[i]); for(intI=1; i<=k2;i++)scanf("%d", &b[i]); for(intI=1; i<=k2;i++) d[a[i]]=i;intCnt=0, len=0; dp[0]=0; for(intj=1; j<=k2;j++) C[j]=d[b[j]]; for(intI=1; i<=k2;i++)/// below for NLGN to find the longest ascending subsequence{if(C[i]>dp[len]) dp[++len]=c[i];Else{intK=lower_bound (dp,dp+len+1, C[i])-DP; Dp[k]=c[i]; } }printf("Case%d:%d\n", ++case,len); }return 0;}
UVA 10635--prince and PRINCESS+NLGN to find the longest common sub-sequence