2016级算法第三次上机-F.ModricWang的导弹防御系统 936 ModricWang的导弹防御系统

思路

题意即为:给出一个长度为n的序列,求出其最长不降子序列。

考虑比较平凡的DP做法:

(nums[i]) 表示这个序列,(f[x]) 表示以第(x)个数为结尾的最长的不降子序列的长度,状态转移方程为:

[f[i]=(max{f[j]}+1) ;;;;;;; mbox{when $nums[i]<=nums[j]$}\ ]

f中的最大值即为答案。

时间复杂度(O(n^2)),空间复杂度(O(n))

当然也可以用时间(O(nlogn))的方法做,不过数据这么小,用(O(n^2))就可以了。

代码

#include <iostream>

using namespace std;

const int MaxN = 1023;

int nums[MaxN], f[MaxN];

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    int n, ans;
    cin >> n;
    for (int i = 0; i < n; i++)
        cin >> nums[i];
    ans = f[0] = 1;
    for (int i = 1; i < n; i++) {
        f[i] = 0;
        for (int j = 0; j < i; j++)
            if (nums[j] >= nums[i] && f[j] >= f[i]) f[i] = f[j] + 1;
        if (f[i] > ans) ans = f[i];
    }
    cout << ans << "
";
}