Pagini recente » Cod sursa (job #2655729) | Cod sursa (job #802840) | Cod sursa (job #1794004) | Cod sursa (job #15018) | Cod sursa (job #2005810)
#include <bits/stdc++.h>
#define maxP 20
#define maxD 10
#define ll long long
using namespace std;
FILE *fin = freopen("ratphu.in", "r", stdin);
FILE *fout = freopen("ratphu.out", "w", stdout);
/* --------------------------------- */
ll n;
int p, nDig[maxD];
/* --------------------------------- */
struct Nod
{
ll conf;
int frq[maxD], r;
};
ll p19[maxD];
queue < Nod > q;
/* --------------------------------- */
map < ll, ll > ans[maxP];
ll sol;
void compP19()
{
p19[0] = 1;
for (int i = 1; i < maxD; ++ i)
p19[i] = p19[i - 1] * 19;
}
void Bfs()
{
q.push(Nod{0, {0, 0, 0, 0, 0, 0, 0, 0, 0, 0}, 0});
ans[0][0] = 1;
while (!q.empty())
{
Nod nod = q.front();
sol = ans[0][nod.conf];
q.pop();
ll add = ans[nod.r][nod.conf];
for (int i = 0; i < maxD; ++ i)
if (nod.frq[i] != nDig[i])
{
Nod newNod = nod;
++ newNod.frq[i];
if (!ans[newNod.r = (nod.r * 10 + i) % p][newNod.conf = nod.conf + p19[i]])
q.push(newNod);
ans[newNod.r][newNod.conf] += add * newNod.frq[i];
}
}
}
int main()
{
scanf("%lld %d", &n, &p);
while (n)
{
++ nDig[n % 10];
n /= 10;
}
compP19();
Bfs();
printf("%lld\n", sol);
return 0;
}