最长递增子序列模板(1)
#include<iostream> #include<algorithm> #include<cstdio> using namespace std; int main() { int n; int ans = 0; int dp[1005]; int num[1005]; scanf("%d",&n); for(int i=0;i<n;i++){ scanf("%d",&num[i]); } dp[0] = 1; int x = 0; for(int i=0;i<n;i++){ ans = 0; for(int j=0;j<i;j++){ if(num[i]>num[j]){ ans = max(dp[j],ans); } } dp[i] = ans+1; if(dp[i]>x) x = dp[i]; } printf("%d",x); return 0; }
最长递增子序列模板2
#include<iostream> #include<algorithm> #include<cstdio> using namespace std; int dp[1005]; int num[1005]; int seach(int start,int end,int n){ while(start<=end){ int mid = (start+end)/2; if(dp[mid]<n){ start++; }else if(dp[mid]>n){ end--; }else{ return mid; } } return start; } int main() { int n; int ans = 0; int l = 1; scanf("%d",&n); for(int i=1;i<=n;i++){ scanf("%d",&num[i]); } dp[l] = num[1]; for(int i=2;i<=n;i++){ int position = seach(1,l,num[i]); dp[position] = num[i]; if(position>l)l++; } printf("%d",l); return 0; }
最长公共子序列模板
#include<iostream> #include<cstdio> #include<cstring> using namespace std; char x[1005],y[1005]; int dp[1005][1005]; int main() { scanf("%s %s",x+1,y+1); x[0]=y[0]='.'; //开头给他们一样的值 int len=strlen(x)>strlen(y)?strlen(x):strlen(y);//最大长度 for(int i=0;i<=len;++i)//初始化数组为0 dp[i][0]=dp[0][i]=0; for(int j,i=1;i<strlen(x);++i) for(j=1;j<strlen(y);++j) if(x[i]==y[j]) dp[i][j]=dp[i-1][j-1]+1; else dp[i][j]=dp[i-1][j]>dp[i][j-1]?dp[i-1][j]:dp[i][j-1]; printf("%d ",dp[strlen(x)-1][strlen(y)-1]); return 0; }
最长公共上升子序列和模板
void time_LICS() //时间优化 { for (int i=1;i<=n;i++) { int ma=0; for (int j=1;j<=n;j++) { if (a[i]==b[j]) f[i][j]=ma+1; else f[i][j]=f[i-1][j]; if (b[j]<a[i] && f[i-1][j]>ma) ma=f[i-1][j]; ans=max(ans,f[i][j]); } } printf("%d ",ans); } void space_LICS() //空间优化 { for (int i=1;i<=n;i++) { int ma=0,tmp; for (int j=1;j<=n;j++) { tmp=ma; if (b[j]<a[i] && f[j]>ma) ma=f[j]; if (a[i]==b[j]) f[j]=tmp+1; ans=max(ans,f[j]); } } printf("%d ",ans); }