a619中等雙向 LIS 與對稱山形子序列

CPE:Wavio Sequence (UVa 10534)

求每個峰頂左右能支撐的嚴格單調長度。

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

解題思路

對每個位置 i,求以它結尾的嚴格遞增子序列長度 L[i],再從右往左做同樣計算得到 R[i],代表以 i 開頭往右嚴格遞減的最大長度。兩側都包含峰頂 i。

Wavio 要求左右等長,所以峰頂 i 的最大長度是 2·min(L[i],R[i])−1,取所有峰頂最大值。LIS 用 tails 陣列與 lower_bound:tails[k] 保持長度 k+1 子序列的最小尾值,插入位置加一即該點的 LIS 長度。相等數字取代同一位置,不能增加長度。每筆 N 後可跨多行讀元素,至 EOF。

Step-by-step animation

示意:1、2、3、2、1

回報動畫錯誤
步驟 1 / 3

由左計算

各點遞增長度為 1、2、3、2、1。

1
2
3
2
1
L
1,2,3,2,1

Reference solution

回報程式錯誤

完整程式

#include <algorithm>
#include <iostream>
#include <vector>
using namespace std;
int main() {
    int n;
    while (cin >> n) {
        vector<int> a(n), left(n), right(n), tails;
        for (int &x : a)
            cin >> x;
        for (int i = 0; i < n; ++i) {
            int p = lower_bound(tails.begin(), tails.end(), a[i]) - tails.begin();
            left[i] = p + 1;
            if (p == (int)tails.size())
                tails.push_back(a[i]);
            else
                tails[p] = a[i];
        }
        tails.clear();
        for (int i = n - 1; i >= 0; --i) {
            int p = lower_bound(tails.begin(), tails.end(), a[i]) - tails.begin();
            right[i] = p + 1;
            if (p == (int)tails.size())
                tails.push_back(a[i]);
            else
                tails[p] = a[i];
        }
        int answer = 1;
        for (int i = 0; i < n; ++i)
            answer = max(answer, 2 * min(left[i], right[i]) - 1);
        cout << answer << '\n';
    }
}

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

更多