Cod sursa(job #465303)

Utilizator bogdan2412Bogdan-Cristian Tataroiu bogdan2412 Data 23 iunie 2010 20:22:01
Problema Ratphu Scor Ascuns
Compilator cpp Status done
Runda Marime 0.92 kb
#include <cstdio>
#include <set>

using namespace std;

#define LL long long

LL N; int P;
LL NR;
int cnt[10];
set<int> left;

inline void back(int k, LL cur = 0, LL curCnt = 1) {
    if (left.empty()) {
        if (cur % P == 0) {
            NR += curCnt;
        }
        return;
    }

    set<int> :: iterator it;
    for (it = left.begin(); it != left.end(); it++) {
        int i = *it;
        cnt[i] -= 1;
        if (cnt[i] == 0) {
            left.erase(it);
        }
        back(k + 1, cur * 10 + i, curCnt * (cnt[i] + 1));
        if (cnt[i] == 0) {
            it = left.insert(i).first;
        }
        cnt[i] += 1;
    }
}

int main() {
    freopen("ratphu.in", "rt", stdin);
#ifndef DEBUG
    freopen("ratphu.out", "wt", stdout);
#endif

    scanf("%lld %d", &N, &P);
    for (; N; N /= 10) {
        left.insert(N % 10);
        cnt[N % 10] += 1;
    }

    NR = 0;
    back(0);

    printf("%lld\n", NR);

    return 0;
}