結果

問題 No.950 行列累乗
ユーザー Leonardone
提出日時 2019-12-13 04:06:04
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
WA  
実行時間 -
コード長 1,853 bytes
コンパイル時間 1,513 ms
コンパイル使用メモリ 96,728 KB
最終ジャッジ日時 2025-01-08 11:13:51
ジャッジサーバーID
(参考情報)
judge2 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 4
other AC * 28 WA * 29
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;


string tos(vector<long long> &a) {
    return to_string(a[0])+","+to_string(a[1])+","+to_string(a[2])+","+to_string(a[3]);
}

void mul(vector<long long> &a, vector<long long> &c, long long p) {
    vector<long long> d(4);
    d[0] = (a[0] * c[0] % p + a[1] * c[2] % p) % p;
    d[1] = (a[0] * c[1] % p + a[1] * c[3] % p) % p;
    d[2] = (c[0] * a[2] % p + c[2] * a[3] % p) % p;
    d[3] = (c[1] * a[2] % p + c[3] * a[3] % p) % p;
    a = d;
}

void modpow(vector<long long> &a, long long k, long long p) {
    if (k > 1) {
        if (k&1) {
            vector<long long> c(a);
            modpow(a, k-1, p);
            mul(a, c, p);
        } else {
            mul(a, a, p);
            modpow(a, k/2, p);
        }
    }
}

int main() {
    long long p;
    vector<long long> a(4), b(4);
    cin >> p;
    for (int i = 0; i < 4; i++) cin >> a[i];
    for (int i = 0; i < 4; i++) cin >> b[i];
    if (a == b) {
        cout << 1 << endl; return 0;
    }
    vector<long long> c(a);
    vector<vector<long long>> s1;
    s1.push_back(a);
    vector<long long> e(a), f(b);
    modpow(e, p-2, p);
    unordered_map<string, int> s2;
    for (int i=1; i <= 1e5; i++) {
        mul(a, c, p);
        s1.push_back(a);
        mul(f, e, p);
        s2[tos(f)] = i;
        if (a == b) {
            cout << (i+1) << endl;
            return 0;
        }
        if (a == c) {
            cout << (-1) << endl;
            return 0;
        }
        
        // cout << a[0] << "," << a[1] << "," << a[2] << "," << a[3] << endl;
    }
    for (int i = 0; i < s1.size(); i++) {
        auto y = s2.find(tos(s1[i]));
        if (y != s2.end()) {
            cout << ((i+1)*y->second) << endl;
            return 0;
        }
    }
    cout << (-1) << endl;
    return 0;
}
0