Cod sursa(job #465711)

Utilizator darrenRares Buhai darren Data 25 iunie 2010 12:25:06
Problema Ratphu Scor 80
Compilator cpp Status done
Runda Stelele Informaticii 2010, gimnaziu si clasa a IX-a, Ziua 1 Marime 1.09 kb
#include<fstream>
#include<string>
#include<queue>
using namespace std;

#define c(i) (n[i] - '0')

string n;
long long p, np[1 << 18][20]; // numarul de posibilitati luand configuratia 'i', sa am restul 'j'
bool sl[1 << 18], ps[1 << 18];
queue<int> q;
int main()
{
	ifstream fin("ratphu.in");
	ofstream fout("ratphu.out");
	fin >> n >> p;
	int s = n.size();
	
	//PD
	for (int i = 0; i < s; ++i)
	{
		np[1 << i][c(i) % p] = 1;
		for (int j = 0; j < s; ++j)
			if (j != i && ps[(1 << i) | (1 << j)] == false)
			{
				q.push((1 << i) | (1 << j));
				ps[(1 << i) | (1 << j)] = true;
			}
	}
	while (!q.empty())
	{
		int now = q.front(); q.pop();
		
		if (sl[now] == false)
		{
			for (int i = 0; i < s; ++i)
				if (now & (1 << i))
					for (int j = 0; j < p; ++j)
						np[now][(j * 10 + c(i)) % p] += np[now ^ (1 << i)][j];
			for (int i = 0; i < s; ++i)
				if ((now & (1 << i)) == 0)
					if (ps[now | (1 << i)] == false)
					{
						q.push(now | (1 << i));
						ps[now | (1 << i)] = true;
					}
			sl[now] = true;
		}
	}

	fout << np[(1 << s) - 1][0];
}