Cod sursa(job #938497)

Utilizator veleanduAlex Velea veleandu Data 12 aprilie 2013 19:10:22
Problema Ratphu Scor 80
Compilator cpp Status done
Runda Arhiva de probleme Marime 1 kb
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

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

#define FORIT( it, v ) for( typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it )

const int max_n=(1<<18);

long long n;
int Mod, i, s, mm, m, nou, st;

bool Viz[max_n];
int El[20], PZ[20];
long long Best[20][max_n];
vector<int> Stare[21];

void mod( int &a ){
	while( a>=Mod )
		a-=Mod;
}

int main(){
	in>>n>>Mod;
	do{
		El[++i] = n%10;
		n/=10;
	}while( n );
	n=i;

	PZ[0]=1;
	for( i=1; i<n; ++i ){
		PZ[i] = 10*PZ[i-1];
		PZ[i] %= Mod;
	}
	
 	Stare[1].push_back( 0 );
	Best[0][0]=1;
	for( s=1; s<=n; ++s ){
 		FORIT( it, Stare[s] ){
			st = *it;
			for( i=0; i<n; ++i ){
				if( !((1<<i)&st) ){
					nou = (1<<i)|st;
					mm = PZ[i]*El[s];
					mod( mm );
					for( m=0; m<Mod; ++m,++mm,mod(mm) ){
						Best[mm][nou] += Best[m][st];
					}
					if( !Viz[nou] ){
						Viz[nou]=1;
						Stare[s+1].push_back(nou);
					}
				}
			}
		}
	}
	out<<Best[0][(1<<n)-1];
	return 0;
}