Cod sursa(job #3379242)

Utilizator TimofeiFilipTimofei Filip Emanuel TimofeiFilip Data 29 noiembrie 2026 21:07:56
Problema Al k-lea termen Fibonacci Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.96 kb
#include<bits/stdc++.h>
using namespace std;

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

typedef long long ll;

const int MOD = 666013;

class Matrix {
private:
    int rows, cols;

public:
    vector<vector<ll>> mat;
    Matrix(int rows, int cols) {
        this->rows = rows;
        this->cols = cols;
        mat.assign(rows, vector<ll>(cols, 0));
    }
    int get_rows() const {
        return rows;
    }

    int get_cols() const {
        return cols;
    }
    void print_matrix() {
        for (auto v : mat) {
            for (auto i : v)
                fout << i << ' ';
            fout << '\n';
        }
    }
    void make_neutral_matrix() {
        assert(rows == cols);
        mat.assign(rows, vector<ll>(cols, 0));

        for (int i = 0; i < rows; i++) {
            mat[i][i] = 1;
        }
    }
    Matrix operator*(const Matrix &other) const {
        assert(cols == other.rows);
        Matrix result(rows, other.cols);

        for (int i = 0; i < rows; i++) {
            for (int k = 0; k < other.rows; k++) {
                for (int j = 0; j < cols; j++) { // cols == other.rows
                    result.mat[i][j] = (result.mat[i][j] + (mat[i][k] * other.mat[k][j]) % MOD) % MOD;
                }
            }
        }
        return result;
    }
};
Matrix pow_matrix(Matrix base, int exp) {
    Matrix result(base.get_rows(), base.get_cols());
    result.make_neutral_matrix();
    while (exp > 0) {
        if (exp % 2 != 0)
            result = result * base;
        base = base * base;
        exp /= 2;
    }
    return result;
}

int main() {
    Matrix fib_matrix(2, 2);
    fib_matrix.mat[0] = {0, 1};
    fib_matrix.mat[1] = {1, 1};

    Matrix start_matrix(1, 2);
    start_matrix.mat[0] = {0, 1};

    int n;
    fin >> n;
    if (n == 0) {
        start_matrix.print_matrix();
        return 0;
    }
    Matrix result = start_matrix * pow_matrix(fib_matrix, n - 2);
    //result.print_matrix();
    fout << result.mat[0][1];

    return 0;
}