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
/* 2021
 * Maciej Szeptuch
 */
#include <algorithm>
#include <cstdio>

int paintings;
int anna;
int costA[131072];
int costB[131072];
char setup[131072];
char current[131072];
long long int score = (1LL << 62);

void solve(int pos, int annas);

int main(void)
{
    scanf("%d %d", &paintings, &anna);
    for(int p = 0; p < paintings; ++p)
        scanf("%d", &costA[p]);

    for(int p = 0; p < paintings; ++p)
        scanf("%d", &costB[p]);

    solve(0, anna);
    printf("%lld\n%s\n", score, setup);
    return 0;
}

void solve(int pos, int annas)
{
    if(pos == paintings || annas == 0)
    {
        while(pos < paintings)
            current[pos++] = 'B';

        long long int best_cost = 0;
        long long int min_prefix = 0;
        long long int total_cost = 0;
        for(int p = 0; p < paintings; ++p)
        {
            total_cost += current[p] == 'A' ? costA[p] : costB[p];
            if(best_cost < total_cost - min_prefix)
                best_cost = total_cost - min_prefix;

            min_prefix = std::min(min_prefix, total_cost);
        }

        if(best_cost < score)
        {
            score = best_cost;
            std::copy(current, current + paintings, setup);
        }

        return;
    }

    if(annas > 0)
    {
        current[pos] = 'A';
        solve(pos + 1, annas - 1);
    }

    current[pos] = 'B';
    solve(pos + 1, annas);
}