1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <iostream>
#include <vector>
#include <string>
using namespace std;
typedef long long ll;

const ll INF = 1LL << 61;

int n, k;
vector<int> c;
vector<int> f;

char C = 'A', F = 'B';

ll DP[50000 + 10];

ll ans;

bool achievable(ll ans) {
    DP[0] = 0;
    for (int i = 0; i < n; i++) {
        if (i + 1 <= k) DP[i+1] = INF;
        bool allinf = true;
        for (int j = min(k, i + 1); j > 0; j--) {
            DP[j] = max(0LL, min(DP[j] + f[i], DP[j-1] + c[i]));
            if (DP[j] > ans) DP[j] = INF;
            else allinf = false;
        }
        DP[0] += f[i];
        if (DP[0] < 0) DP[0] = 0;
        if (DP[0] > ans) DP[0] = INF;
        else allinf = false;
        if (allinf) return false;
    }

    return DP[k] <= ans;
}

vector<vector<bool>> which;

void recover() {
    DP[0] = 0;
    for (int i = 0; i < n; i++) {
        if (i + 1 <= k) DP[i+1] = INF;
        for (int j = min(k, i + 1); j > 0; j--) {
            which[i][j] = DP[j] + f[i] > DP[j-1] + c[i];
            DP[j] = max(0LL, min(DP[j] + f[i], DP[j-1] + c[i]));
            if (DP[j] > ans) DP[j] = INF;
        }
        DP[0] += f[i];
        if (DP[0] < 0) DP[0] = 0;
        if (DP[0] > ans) DP[0] = INF;
    }
}

ll find_ans(ll hi) {
    if (hi <= 0) return 0;
    ll lo = 0;
    while (lo + 1 < hi) {
        //cerr << "lo = " << lo << ", " << "hi = " << hi << endl;
        ll mid = (lo + hi) / 2;
        if (achievable(mid)) hi = mid;
        else lo = mid;
    }
    return hi;
}

int main() {
    std::ios::sync_with_stdio(false); std::cin.tie();
    cin >> n >> k;
    c.resize(n); f.resize(n);
    for (int i = 0; i < n; i++) cin >> c[i];
    for (int i = 0; i < n; i++) cin >> f[i];
    ll S = 0;
    for (int i = 0; i < n; i++) S += max(c[i], f[i]);

    if (k > n-k) {
        k = n-k;
        swap(c, f); swap(C, F);
    }


    ans = find_ans(S);
    cout << ans << '\n';
    which.resize(n);
    for (int i = 0; i < n; i++) which[i].resize(k+1);
    recover();
    string sol;
    sol.resize(n);
    int j = k;
    for (int i = n - 1; i >= 0; i--) {
        if (which[i][j]) {
            sol[i] = C; j--;
        } else {
            sol[i] = F;
        }
    }
    cout << sol << '\n';
}