华为机试题 合唱队

简介

动态规划, 用到了最长子序列长度.

用两个for循环就可以得到最长子序列.

参考链接

https://blog.csdn.net/feengg/article/details/80866483

code

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main() {
    int n;
    while(cin >> n){
        vector<int> v;
        vector<int> dp1(n, 1);
        vector<int> dp2(n, 1);
        int t;
        for(int i=0; i<n; i++){
            cin >> t;
            v.emplace_back(t);
        }
        // 计算正向位置
        for(uint16_t i = 0; i<n; i++){
            for(uint16_t j=0; j<i; j++){
                if(v[j] < v[i] && dp1[j] >= dp1[i]) {
                    dp1[i] = dp1[j] + 1;
                }
            }
        }
        // 计算反向位置
        reverse(v.begin(), v.end());
        for(uint16_t i = 0; i<n; i++){
            for(uint16_t j=0; j<i; j++){
                if(v[j] < v[i] && dp2[j] >= dp2[i]) {
                    dp2[i] = dp2[j] + 1;
                }
            }
        }
        reverse(v.begin(), v.end());
        reverse(dp2.begin(), dp2.end());
        int max = 0;
        int maxIdx = 0;
        for(int i=0; i<n; i++){
            int sum = dp1[i] + dp2[i];
            if(sum > max){
                maxIdx = i;
                max = sum;
            }
        }
        cout << n - max + 1 << endl;
    }
}
Hope is a good thing,maybe the best of things,and no good thing ever dies.----------- Andy Dufresne
原文地址:https://www.cnblogs.com/eat-too-much/p/14930025.html