HDU 1423 Greatest Common Increasing Subsequence
最长公共上升子序列。
O(n*n*n)
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-8; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } inline int read() { char c = getchar(); while(!isdigit(c)) c = getchar(); int x = 0; while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); } return x; } const int maxn=550; int dp[maxn][maxn]; int T,ans,len1,len2,a[maxn],b[maxn]; int main() { scanf("%d",&T); while(T--) { scanf("%d",&len1); for(int i=1;i<=len1;i++) scanf("%d",&a[i]); scanf("%d",&len2); for(int i=1;i<=len2;i++) scanf("%d",&b[i]); memset(dp,ans=0,sizeof dp); for(int i=1;i<=len1;i++) { for(int j=1;j<=len2;j++) { if(a[i]!=b[j]) dp[i][j]=dp[i-1][j]; else { for(int s=0;s<=j-1;s++) { if(b[s]>=b[j]) continue; dp[i][j]=max(dp[i][j],dp[i-1][s]+1); } } ans=max(ans,dp[i][j]); } } printf("%d\n",ans); if(T>0) printf("\n"); } return 0; }
优化后O(n*n)
#pragma comment(linker, "/STACK:1024000000,1024000000") #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<vector> #include<map> #include<set> #include<queue> #include<stack> #include<iostream> using namespace std; typedef long long LL; const double pi=acos(-1.0),eps=1e-8; void File() { freopen("D:\\in.txt","r",stdin); freopen("D:\\out.txt","w",stdout); } inline int read() { char c = getchar(); while(!isdigit(c)) c = getchar(); int x = 0; while(isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); } return x; } const int maxn=550; int dp[maxn][maxn],f[maxn][maxn]; int T,ans,len1,len2,a[maxn],b[maxn]; int main() { scanf("%d",&T); while(T--) { scanf("%d",&len1); for(int i=1;i<=len1;i++) scanf("%d",&a[i]); scanf("%d",&len2); for(int i=1;i<=len2;i++) scanf("%d",&b[i]); memset(dp,ans=0,sizeof dp); memset(f,0,sizeof f); for(int i=1;i<=len1;i++) { int MAX=0; for(int j=1;j<=len2;j++) { if(a[i]!=b[j]) dp[i][j]=dp[i-1][j]; else dp[i][j]=MAX+1; if(a[i]>b[j]) MAX=max(MAX,dp[i][j]); ans=max(ans,dp[i][j]); } } printf("%d\n",ans); if(T) printf("\n"); } return 0; }