LIS: the longest ascending subsequence problem
Boundary processing : f[0]=0;
Method 1 : Consider what states can be derived from f[i]
for(int i = 0; i < n; i++) i:结尾下标
for(int j = i + 1; j <= n; j++) 下一个数
if(a[j] > a[i]) f[j]=max(f[j],f[i]+1);
Method 2 : Consider which states f[i] can be obtained from.
This method is more commonly used
for(int i = 1; i <= n; i++)
for(int j = 0;j < i;j++) 前一个数
if(a[j] < a[i]) f[i]=max(f[i],f[j]+1);
aims
for(int i=1;i<=n;i++) ans=max(ans,f[i]);
What is the optimal solution?
for(int i=1;i<=n;i++)
{
for(int j=0;j<i;j++)
{
if(a[j]>a[i])
if(f[j]+1>f[i]){
f[i]=f[j]+1;
pos[i]=j;//记录由某点推导过来的该点的下标
}
}
}
void print(int i)
{
if(i==0) return ;
print(pos[i]);//递归处理
cout<<a[i]<<" ";
}
int ans=0,tail;
for(int i=1;i<=n;i++)
if(f[i]>ans) ans=f[i],tail=i;
cout<<ans<<endl;
print(tail);
Dichotomous optimization
q [ i ] q[i] q [ i ] represents the number at the end of the ascending subsequence of length i, the number in the enumerated sequencea [i] a[i]a [ i ] , put it inqqThe largest in the q array is less thana [i] a[i]After the number of a [ i ] , it is realized by dichotomy. Time complexitynlogn nlognn l o g n .
for(int i=1;i<=n;i++) cin>>a[i];
int len=0;
for(int i=1;i<=n;i++)
{
int l=0,r=len;
while(l<r)
{
int mid=(l+r+1)>>1;
if(q[mid]<a[i]) l=mid;
else r=mid-1;
}
len=max(len,r+1);
q[r+1]=a[i];
}
cout<<len;
LCS: Longest Common Subsequence Problem
Border processing :
for(int i = 0; i <= n; i++) f[i][0]=0;
for(int j = 0; j <= m; j++) f[0][j]=0;
State transition
for(int i = 1;i <= n;i++)
for(int j=1; j<= m ;j++)
f[i][j]=max(f[i-1][j],f[i][j-1]);
if(a[i] == a[j]) f[i][j]=max(f[i][j],f[i-1][j-1]+1);
aims
cout<<f[n][m]<<endl;
Digital triangle model
Idea The
current coordinates (i,j) can go to (i+1,j) (i+1,j+1)
Boundary processing
f[1][1]=a[1][1]
State transition
for(int i = 1;i<n;i++)
for(int j=1;j<=i;j++){
f[i+1][j]=max(f[i+1][j],f[i][j]+a[i+1][j]);
f[i+1][j+1]=max(f[i+1][j+1],f[i][j]+a[i+1][j+1]);
}
Target result
int ans=0;
for(int j=1;j<=n;j++)
ans=max(ans,f[n][j]);