a571中等以第一節車廂為中心的雙向單調子序列

CPE:Trainsorting (UVa 11456)

從後往前求可接到前端與後端的最大車廂數。

前往題目練習 →回報教學錯誤時間 O(n²),空間 O(n)。

解題思路

固定某節i為第一個保留的車廂,之後抵達且比它重的車廂只能依越來越重的順序接前端;比它輕的只能依越來越輕的順序接後端。這兩側互不影響,因此可以把從i開始、依抵達順序的最長遞增與最長遞減子序列相加,再減去重複的i。

由右往左算inc[i]、dec[i]。對所有j>i,若w[j]>w[i],用1+inc[j]更新inc[i];若較小則更新dec[i]。最後取max(inc[i]+dec[i]−1)。陣列向右代表未來抵達者,不能誤用已抵達而被放棄的車廂。n=0時沒有中心點,答案0。

Step-by-step animation

示意:依序抵達3、1、4、2

回報動畫錯誤
步驟 1 / 3

最右兩節

2本身長1;4之後可接較輕的2,dec(4)=2。

4:inc1 dec2
2:inc1 dec1
已算位置
2、3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <string>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <cmath>
#include <iomanip>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <unordered_map>
#include <unordered_set>
#include <array>
#include <tuple>
#include <functional>
#include <limits>
#include <cstdint>
#include <cctype>
#include <utility>
using namespace std;

int main() {
    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<long long> w(n);
        for (auto &x : w)
            cin >> x;
        vector<int> inc(n, 1), dec(n, 1);
        int ans = 0;
        for (int i = n - 1; i >= 0; --i) {
            for (int j = i + 1; j < n; ++j) {
                if (w[j] > w[i])
                    inc[i] = max(inc[i], inc[j] + 1);
                if (w[j] < w[i])
                    dec[i] = max(dec[i], dec[j] + 1);
            }
            ans = max(ans, inc[i] + dec[i] - 1);
        }
        cout << ans << '\n';
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多