DP—最长下降子序列(代码)

原理和最长上升子序列一样,排序和二分时比较方法改一下即可

#include 
#include 
int arr[1003],ans[1003];
using namespace std;
int binary_search(int i,int len){
    int left,right,mid;
    left = 0,right = len;
    while(left < right){
        mid = left + (right - left) / 2;
        if(ans[mid] <= arr[i])
            right = mid;
        else
            left = mid + 1;
    }
    return left;
}
int main()
{
    int n;
    while(cin >> n){
        int len = 1;
        for(int i = 1;i <= n;i++)
            cin >> arr[i];
        ans[1] = arr[1];
        for(int i = 2;i <= n;i++){
            if(arr[i] < ans[len])
                ans[++len] = arr[i];
            else{
                int pos = binary_search(i, len);
                ans[pos] = arr[i];
            }
        }
        cout << len <for(int i = 1;i <= len;i++)
            cout << ans[i] << " ";
    }
}

你可能感兴趣的:(DP—最长下降子序列(代码))