这道题实质上是求解给定序列中的的最长不增子序列的长度。
首先需要注意的是子序列和子数组的区别。子序列是不要求元素之间的连续性。
这道题的求解过程中还是利用了动态规划的思想,也可以进一步学习一下?
究竟什么是状态转移方程???
其实一般的状态转移方程都是由子状态到父状态,可以是1对1,也开始2对1,但是更为普遍的其实是n对1
比如常见的max函数,利用所有子状态的遍历来求解父亲状态,因为大概率情况下,父亲状态都具有某方面有最值的特性。
在求解状态转移方程的时候,一定要特别注意子状态和父亲状态之间的关系!
#include <algorithm> #include <iostream> using namespace std; const int maxlen = 1e6; int ar[maxlen]; int dp[maxlen];//其中dp数组代表的是序列中以ar[i]为最后一个元素最长不增子序列长度 int main() { // 最长不增子序列 int n,i,j,k; scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&ar[i]); for(i=1;i<=n;i++) dp[i]=1; for(i=2;i<=n;i++) for(j=1;j<i;j++) if(ar[j] > ar[i]) dp[i]=max(dp[i],dp[j]+1); int ans=0; for(i=1;i<=n;i++) if(ans < dp[i]) ans=dp[i]; printf("%d ",ans); return 0; }