合唱队问题

本文介绍了一种求解最长递增子序列和最长递减子序列之和最大化的算法,通过双遍历的方式,先从左到右计算最长递增子序列长度,再从右到左计算最长递减子序列长度,最后找出中间点使得两边子序列之和最大。
8
186 186 150 200 160 130 197 200
               </pre></td></tr><tr><td class="grid_left_td">样例输出:</td><td><pre>4

                </pre></td></tr></tbody></table>
根据题意可知,我们需要求出一个“中间点”,使得其左边的【最长递增子序列】和其右边的【最长递减子序列】之和最大。

    #include <iostream>  
    #include <vector>  
    using namespace std;  
      
    int LonggestIncreaseLength(vector<int> &vec) {  
        vector<int> result(vec.size(), 1);  
        vector<int> result2(vec.size(), 1);  
        for (int i = 1; i < vec.size(); i++) {  
            for (int j = 0; j < i; j++) {  
                if (vec[i] > vec[j] && result[i] < result[j] + 1)  
                    result[i] = result[j] + 1;  
            }  
        }  
      
        for (int i = vec.size() - 2; i >= 0; --i) {  
            for (int j = vec.size() - 1; j > i; --j) {  
                if (vec[i] > vec[j] && result2[i] < result2[j] + 1)  
                    result2[i] = result2[j] + 1;  
            }  
        }  
        int max = 0;  
        for (int i = 0; i < vec.size(); i++) {  
            if (max < result[i] + result2[i])  
                max = result[i] + result2[i];  
        }  
        return vec.size() - max + 1;  
    }  
    int main() {  
        int n;  
        cin >> n;  
        if (n <= 0)  
            return 0;  
        vector<int> ivec(n);  
        for (int i = 0; i < n; i++)  
            cin >> ivec[i];  
        cout << LonggestIncreaseLength(ivec) << endl;  
    }  

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值