Cod sursa(job #1534475)

Utilizator tamionvTamio Vesa Nakajima tamionv Data 23 noiembrie 2015 19:08:02
Problema Lista lui Andrei Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.34 kb
// O(sigma ^ 3 * log(n))

#include <fstream>
#include <array>
#include <numeric>
using namespace std;

constexpr int mod = 104659;
constexpr int sigma = 26;

template <long unsigned int sz>
using mat = array<array<int, sz>, sz>;

template <long unsigned int sz>
mat<sz> mult(const mat<sz>& a, const mat<sz>& b){
	mat<sz> rez = {}, tr = {};
	for(int i = 0;  i < sz; ++i){
		for(int j = 0; j < sz; ++j){
			tr[i][j] = b[j][i]; } }
	for(int i = 0; i < sz; ++i){
		for(int j = 0; j < sz; ++j){
			long long tmp = 0;
			for(int k = 0; k < sz; ++k){
				tmp += a[i][k] * tr[j][k]; }
			rez[i][j] = tmp%mod; } }
	return rez; }

template <long unsigned int sz>
mat<sz> exponent(mat<sz> baza, int x){
	mat<sz> rez = {};
	for(int i = 0; i < sz; ++i){
		rez[i][i] = 1; }
	for( ; x > 0; x /= 2, baza = mult(baza, baza)){
		if(x%2 == 1){
			rez = mult(baza, rez); } }
	return rez; }

int main(){
	ifstream f("nrcuv.in");
	ofstream g("nrcuv.out");

	int n, m;
	f >> n >> m;

	mat<sigma> graf;
	for(int i = 0; i < sigma; ++i){
		for(int j = 0; j < sigma; ++j){
			graf[i][j] = 1; } }

	for(int i = 0; i < m; ++i){
		char a, b;
		f >> a >> b;
		a -= 'a', b -= 'a';
		graf[a][b] = graf[b][a] = 0; }

	const auto mat_rez = exponent(graf, n-1);
	long long rez = 0;
	for(int i = 0; i < sigma; ++i){
		for(int j = 0; j < sigma; ++j){
			rez += mat_rez[i][j]; } }

	g << (rez%mod);

	return 0; }