Cod sursa(job #1857138)

Utilizator iordache.bogdanIordache Ioan-Bogdan iordache.bogdan Data 25 ianuarie 2017 20:51:54
Problema Expresii 2 Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.79 kb
#include <fstream>
#include <vector>
#include <cstring>
#include <algorithm>

int length, charCount;
long long order;

long long dp[35][35][3];
//dp[i][j][k] := number of configurations with last i positions fixed
//				j variables needed to be inserted
//				(length - i)th position is 0:variable, 1:* or +, 2:!

void ComputeDp() {
	dp[0][1][0] = 1;
	for (int i = 1; i <= length; ++i) {
		for (int j = 0; j <= length; ++j) {
			//try to insert variable
			if (j < length)
				for (int k : {0, 1, 2})
					dp[i][j][0] += dp[i - 1][j + 1][k] * charCount;

			//try to insert + or *
			if (j > 1)
				for (int k : {0, 1, 2})
					dp[i][j][1] += dp[i - 1][j - 1][k] * 2;

			//try to insert !
			if (j > 0)
				for (int k : {0, 1, 2})
					dp[i][j][2] += dp[i - 1][j][k];
		}
	}
}

std::string GetConfiguration() {
	std::string res;
	int setVariables = 0;

	for (int i = 0; i < length; ++i) {
		int curr = 0;
		while (curr < charCount && dp[length - i][setVariables][0] / charCount < order) {
			order -= dp[length - i][setVariables][0] / charCount;
			curr++;
		}

		if (curr < charCount) {
			setVariables++;
			res += char('A' + curr);
			continue;
		}

		curr = 0;
		while (curr < 2 && dp[length - i][setVariables][1] / 2 < order) {
			order -= dp[length - i][setVariables][1] / 2;
			curr++;
		}

		if (curr < 2) {
			setVariables--;
			res += (curr == 0 ? "+" : "*");
		}
		else
			res += "!";
	}

	return res;
}

int main() {
	std::ifstream inputFile("expresii2.in");
	std::ofstream outputFile("expresii2.out");

	inputFile >> length >> charCount >> order;
	ComputeDp();
	outputFile << dp[length][0][0] << '\n';
	outputFile << GetConfiguration() << '\n';

	inputFile.close();
	outputFile.close();

	return 0;
}

//Trust me, I'm the Doctor!