Cod sursa(job #466035)

Utilizator Mishu91Andrei Misarca Mishu91 Data 25 iunie 2010 19:42:07
Problema Ratphu Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.31 kb
#include <fstream>

using namespace std;

const int MAX_P = 20;
const int MAX_N = (1 << 18);

ifstream fin ("ratphu.in");
ofstream fout ("ratphu.out");

long long N, R[MAX_N][MAX_P];
int P, Ncf;
char cif[MAX_P];
char pow10[MAX_P];

void trans(long long N) {
	for(; N; N /= 10) {
		cif[Ncf++] = N % 10;
	}
}

/*long long calc(int conf, int rest, int nr) {
	if(viz[conf][rest]) return R[conf][rest];
	viz[conf][rest] = 1;

    for(int i = 0; i < Ncf; ++i) {
		if(conf & (1 << i)) {
			int actr = (pow10[nr-1] * cif[i]) % P;
			int newr = (rest - actr + P) % P;

			R[conf][rest] += calc(conf ^ (1 << i), newr, nr-1);
		}
	}

	return R[conf][rest];
} */

int main() {
	fin >> N >> P;
	trans(N);
	R[0][0] = 1;
	
	pow10[0] = 1;
	for(int i = 1; i <= 18; ++i)
		pow10[i] = (pow10[i-1] * 10) % P; 

   // fout << calc((1 << Ncf)-1, 0, Ncf);



   for(int conf = 1; conf < (1 << Ncf); ++conf) {
		int nr = 0, aux = conf;
		for(int i = 0; i < Ncf; ++i) {
			if(aux & 1) {
				++nr;
			}

			aux >>= 1;
		}

		aux = conf;
		for(int i = 0; i < Ncf; ++i) {
			for(int r = 0; r < P; ++r) {
				if(R[conf ^ (1 << i)][r] == 0) continue;
				if(aux & 1) {
					int actr = (pow10[nr-1]*cif[i]) % P;
					int newr = (actr + r) % P;
					R[conf][newr] += R[conf ^ (1 << i)][r];
				}             
			}

			aux >>= 1;
		}
	}

	fout << R[(1 << Ncf)-1][0];   
}