華為機試題 合唱隊
阿新 • • 發佈:2021-06-25
簡介
動態規劃, 用到了最長子序列長度.
用兩個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; } }