제출 #211508

#제출 시각아이디문제언어결과실행 시간메모리
211508JustInCase건물 4 (JOI20_building4)C++17
100 / 100
312 ms26092 KiB
#include <bits/stdc++.h>

const int32_t MAX_N = 1e6;
const int32_t INF = 2e9;

int32_t dp[MAX_N + 5][2][2];

int main() {
    std::ios_base::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int32_t n;
    std::cin >> n;

    n *= 2;

    std::vector< int32_t > a(n);
    for(int32_t i = 0; i < n; i++) {
        std::cin >> a[i];
    }

    std::vector< int32_t > b(n);
    for(int32_t i = 0; i < n; i++) {
        std::cin >> b[i];
    }

    dp[0][0][0] = 1;
    dp[0][0][1] = 1;
    dp[0][1][0] = 0;
    dp[0][1][1] = 0;

    for(int32_t i = 1; i < n; i++) {
        dp[i][0][0] = INF;
        dp[i][0][1] = -1;
        dp[i][1][0] = INF;
        dp[i][1][1] = -1;

        if(a[i - 1] <= a[i]) {
            dp[i][0][0] = std::min(dp[i][0][0], dp[i - 1][0][0] + 1);
            dp[i][0][1] = std::max(dp[i][0][1], dp[i - 1][0][1] + 1);
        }
        if(a[i - 1] <= b[i]) {
            dp[i][1][0] = std::min(dp[i][1][0], dp[i - 1][0][0]);
            dp[i][1][1] = std::max(dp[i][1][1], dp[i - 1][0][1]);
        }
        if(b[i - 1] <= a[i]) {
            dp[i][0][0] = std::min(dp[i][0][0], dp[i - 1][1][0] + 1);
            dp[i][0][1] = std::max(dp[i][0][1], dp[i - 1][1][1] + 1);
        }
        if(b[i - 1] <= b[i]) {
            dp[i][1][0] = std::min(dp[i][1][0], dp[i - 1][1][0]);
            dp[i][1][1] = std::max(dp[i][1][1], dp[i - 1][1][1]);
        }
    }

    int32_t cntA = 0, lastVal;
    std::string res;
    if(dp[n - 1][0][0] <= n / 2 && dp[n - 1][0][1] >= n / 2) {
        cntA = 1;
        lastVal = a[n - 1];
        res = "A";
    }
    else if(dp[n - 1][1][0] <= n / 2 && dp[n - 1][1][1] >= n / 2) {
        res = "B";
        lastVal = b[n - 1];
    }
    else {
        std::cout << -1 << '\n';
        return 0;
    }

    for(int32_t i = n - 2; i >= 0; i--) {
        if(a[i] <= lastVal && dp[i][0][0] <= n / 2 - cntA && dp[i][0][1] >= n / 2 - cntA) {
            res += 'A';
            cntA++;
            lastVal = a[i];
        }
        else {
            res += 'B';
            lastVal = b[i];
        }
    }

    std::reverse(res.begin(), res.end());
    std::cout << res << '\n';
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...