結果

問題 No.3061 Cut and Maximums
ユーザー 👑 rin204
提出日時 2024-07-07 18:45:18
言語 C++23
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 144 ms / 2,000 ms
コード長 2,214 bytes
コンパイル時間 3,727 ms
コンパイル使用メモリ 260,472 KB
実行使用メモリ 34,040 KB
最終ジャッジ日時 2024-07-07 18:45:27
合計ジャッジ時間 8,245 ms
ジャッジサーバーID
(参考情報)
judge1 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 3
other AC * 33
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <bits/stdc++.h>
using namespace std;

template <typename T>
std::vector<int> CartesianTree(std::vector<T> &A) {
    int n = A.size();
    std::stack<std::pair<T, int>> st;
    std::vector<int> par(n, -1);

    for (int i = 0; i < n; i++) {
        while (!st.empty() && A[i] < st.top().first) {
            int j = st.top().second;
            st.pop();
            if (!st.empty() && A[i] < st.top().first) {
                par[j] = st.top().second;
            } else {
                par[j] = i;
            }
        }
        st.push({A[i], i});
    }

    while (st.size() >= 2u) {
        int i = st.top().second;
        st.pop();
        par[i] = st.top().second;
    }

    int i  = st.top().second;
    par[i] = i;
    return par;
}

int main() {
    int n;
    cin >> n;
    assert(1 <= n and n <= 300000);
    vector<int> P(n);
    vector<bool> used(n);
    for (int i = 0; i < n; i++) {
        cin >> P[i];
        assert(1 <= P[i] and P[i] <= n);
        P[i]--;
        assert(!used[P[i]]);
        used[P[i]] = true;
    }
    string S;
    cin >> S;
    assert(S.size() == n);
    for (auto c : S) {
        assert(c == 'B' or c == 'W');
    }

    if (S[n - 1] == 'W') {
        for (auto c : S) {
            if (c == 'B') {
                cout << -1 << endl;
                return 0;
            }
        }
        cout << 0 << endl;
        return 0;
    }

    {
        int p = find(P.begin(), P.end(), n - 1) - P.begin();
        rotate(P.begin(), P.begin() + p, P.end());
    }

    vector<int> minus_P(n);
    for (int i = 0; i < n; i++) {
        minus_P[i] = -P[i];
    }

    auto ct = CartesianTree(minus_P);
    vector<vector<int>> child(n);
    for (int i = 0; i < n; i++) {
        if (ct[i] != i) {
            child[ct[i]].push_back(i);
        }
    }

    auto dfs = [&](auto &&self, int pos) -> int {
        int ret = 0;
        for (auto npos : child[pos]) {
            auto res = self(self, npos);
            if (S[P[pos]] == 'B')
                ret = max(ret, res);
            else
                ret += res;
        }
        if (S[P[pos]] == 'B') ret = max(ret, 1);
        return ret;
    };

    auto ans = dfs(dfs, 0);
    cout << ans << endl;
}
0