結果

問題 No.551 夏休みの思い出(2)
ユーザー pekempeypekempey
提出日時 2017-07-28 23:14:13
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 32 ms / 4,000 ms
コード長 1,992 bytes
コンパイル時間 606 ms
コンパイル使用メモリ 75,100 KB
実行使用メモリ 6,820 KB
最終ジャッジ日時 2024-10-10 04:46:33
合計ジャッジ時間 2,722 ms
ジャッジサーバーID
(参考情報)
judge4 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 47
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>

int modpow(int a, int b, int m) {
    int ret = 1;
    while (b > 0) {
        if (b & 1) ret = 1LL * ret * a % m;
        a = 1LL * a * a % m;
        b /= 2;
    }
    return ret;
}

int modinv(int a, int m) {
    return modpow(a, m - 2, m);
}

bool issquare(int a, int p) {
    return modpow(a, (p - 1) / 2, p) == 1;
}

int modsqrt(int a, int p) {
    if (a == 0) return 0;
    if (p == 2) return a;
    if (!issquare(a, p)) return -1;
    int b = 2;
    while (issquare((1LL * b * b - a + p) % p, p)) b++;
    int w = (1LL * b * b - a + p) % p;

    auto mul = [&](std::pair<int, int> u, std::pair<int, int> v) {
        int a = (1LL * u.first * v.first + 1LL * u.second * v.second % p * w) % p;
        int b = (1LL * u.first * v.second + 1LL * u.second * v.first) % p;
        return std::make_pair(a, b);
    };

    // (b + sqrt(b^2-a))^(p+1)/2
    int e = (p + 1) / 2;
    auto ret = std::make_pair(1, 0);
    auto v = std::make_pair(b, 1);
    while (e > 0) {
        if (e & 1) ret = mul(ret, v);
        v = mul(v, v);
        e /= 2;
    }
    return ret.first;
}

int main() {
    int p, r;
    std::cin >> p >> r;

    auto f = [&](long long x) {
        x %= p;
        if (x < 0) {
            x += p;
        }
        return x;
    };

    int q;
    std::cin >> q;
    while (q--) {
        long long a, b, c;
        scanf("%lld %lld %lld", &a, &b, &c);

        long long d = f(b * b - 4 * a * c);

        if (d == 0) {
            long long x1 = f(f(-b) * modinv(f(2 * a), p));
            printf("%lld\n", x1);
        } else if (!issquare(d, p)) {
            puts("-1");
            continue;
        } else {
            d = modsqrt(d, p);
            long long x1 = f(f(-b + d) * modinv(f(2 * a), p));
            long long x2 = f(f(-b - d) * modinv(f(2 * a), p));
            if (x1 > x2) std::swap(x1, x2);
            printf("%lld %lld\n", x1, x2);
        }
    }
}
0