Cod sursa(job #594981)

Utilizator SpiderManSimoiu Robert SpiderMan Data 10 iunie 2011 18:13:07
Problema Expresii 2 Scor 40
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.5 kb
# include <cstdio>
# include <cstring>
# include <map>
# include <string>
using namespace std ;

typedef long long ll;
const char *FIN = "expresii2.in", *FOU = "expresii2.out" ;
const int MAX = 35;

int N, K;
char A[MAX], B[MAX] ;
map <string, ll> M[MAX];
ll solution, P;

inline bool mare (char S) {
    return (S >= 'A' && S <= 'Z') ;
}

inline bool check (string S, int N, char ch) {
    return (S.size () < N || (S.size () == N && S[N - 1] == ch));
}

ll doit (int N, string S) {
    ll sol = 0;
    if (N == 1) return S.size () ? (mare (S[0]) ? 1 : 0) : K;
    if (M[N].count (S) > 0) return M[N][S];
    if (S.size () < N || (S.size () == N && S[N - 1] == '!'))
        sol = doit (N - 1, S.substr  (0, N - 1));
    for (int i = 1, j = check (S, N, '+') + check (S, N, '*'); i < N - 1; ++i) {
        sol += j * doit (i, S.substr  (0, i)) * doit (N - i - 1, S.size () < i ? "" : S.substr  (i, N - i - 1));
    }
    M[N][S] = sol;
    return sol;
}

int main (void) {
    fscanf (fopen (FIN, "r"), "%d %d %lld", &N, &K, &P) ;
    freopen (FOU, "w", stdout) ;
    printf ("%lld\n", doit (N, ""));
    for (int i = 0; i < K; ++i)
        A[i] = 'A' + i;
    A[K] = '+', A[K + 1] = '*', A[K + 2] = '!';
    for (int i = 0; i < N; ++i) {
        for (int j = 0, k; j <= K + 2; ++j) {
            B[i] = A[j], k = doit (N, B) ;
            if (P <= (solution += k)) {
                solution -= k;
                break ;
            }
        }
    }
    printf ("%s", B) ;
}