結果

問題 No.181 A↑↑N mod M
ユーザー snrnsidy
提出日時 2021-04-23 05:25:41
言語 C++17
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 3 ms / 5,000 ms
コード長 1,716 bytes
コンパイル時間 2,720 ms
コンパイル使用メモリ 133,596 KB
最終ジャッジ日時 2025-01-20 23:09:07
ジャッジサーバーID
(参考情報)
judge5 / judge4
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 6
other AC * 37
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <map>
#include <set>
#include <list>
#include <cmath>
#include <ctime>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <cstdio>
#include <limits>
#include <vector>
#include <cstdlib>
#include <numeric>
#include <sstream>
#include <iostream>
#include <algorithm>
#include <functional> 
#include <iomanip>
#include <unordered_map>
#include <memory.h>
#include <unordered_set>
#include <fstream>
#include <random>

using namespace std;

#define repeat(i,n) for (int i = 0; (i) < int(n); ++(i))
using ll = long long;
using namespace std;
struct sequence {
    vector<int> data;
    int offset, cycle;
};
sequence iterate(int a, function<int(int)> f) {
    sequence xs;
    unordered_map<int, int> used;
    while (not used.count(a)) {
        used[a] = xs.data.size();
        xs.data.push_back(a);
        a = f(a);
    }
    xs.offset = used[a];
    xs.cycle = xs.data.size() - xs.offset;
    return xs;
}
int at(sequence const& xs, int i) {
    return xs.data[i < xs.offset ? i : (i - xs.offset) % xs.cycle + xs.offset];
}
double tet(int a, int n) {
    double acc = 1;
    repeat(i, n) {
        acc = pow(a, acc);
        if (isinf(acc)) break;
    }
    return acc;
}
int tetmod(int a, int n, int m) {
    if (m == 1) return 0;
    if (n == 0) return 1;
    if (a == 0) return 0;
    if (a == 1) return 1;
    double estimated = tet(a, n - 1);
    sequence powmod = iterate(1, [&](int x) { return a * (ll)x % m; });
    ll b = tetmod(a, n - 1, powmod.cycle);
    int i = estimated < powmod.offset ? estimated : b + powmod.offset * powmod.cycle;
    return at(powmod, i);
}
int main() {
    int a, n, m; cin >> a >> n >> m;
    cout << tetmod(a, n, m) << '\n';
    return 0;
}
0