Cod sursa(job #595144)

Utilizator cont_de_testeCont Teste cont_de_teste Data 11 iunie 2011 12:14:31
Problema Expresii 2 Scor 20
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.76 kb
# include <map>
# include <string>
# include <fstream>
# include <ext/hash_map>
# include <cstring>
using namespace std ;
using namespace __gnu_cxx;

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

int N, K;
string A, B ;

ll solution, P, k;

const int r1 = 6007;
const int r2 = 10301;

struct eqstr
{
  bool operator()(const char* s1, const char* s2) const
  {
    return strcmp(s1, s2) == 0;
  }
};

hash_map<const char*, int, hash<const char*>, eqstr> M[MAX];

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

ll doit (int N, string S) {
    ll sol = 0;
    if (N == 1) return S.size () ? (S[0] >= 'A' && S[0] <= 'Z' ? 1 : 0) : K;
    if (M[N].count (S.c_str()) > 0) return M[N][S.c_str()];
    if ((int) S.size () < N || ((int) 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, (int) S.size () < i ? "" : S.substr  (i, N - i - 1));
    }
    M[N][S.c_str()] = sol;
    return sol;
}

int main (void) {
    ifstream f (FIN) ;
    f >> N >> K >> P ;
    fscanf (fopen (FIN, "r"), "%d %d %lld", &N, &K, &P) ;
    ofstream g (FOU) ;
    g << doit (N, "") << "\n";
    for (int i = 0; i < K; ++i) A += 'A' + i;
    A += '+', A += '*', A += '!';
    for (int i = 0; i < N; ++i) {
        B += " ";
        for (int j = 0; j < K + 3; ++j) {
            B[i] = A[j], k = doit (N, B) ;
            if (P <= (solution += k)) {
                solution -= k;
                break ;
            }
        }
    }
    g << B ;
}