結果

問題 No.551 夏休みの思い出(2)
ユーザー pekempey
提出日時 2017-07-29 00:40:53
言語 C++14
(gcc 13.3.0 + boost 1.87.0)
結果
AC  
実行時間 32 ms / 4,000 ms
コード長 1,776 bytes
コンパイル時間 643 ms
コンパイル使用メモリ 69,768 KB
実行使用メモリ 5,248 KB
最終ジャッジ日時 2024-10-10 11:15:38
合計ジャッジ時間 2,711 ms
ジャッジサーバーID
(参考情報)
judge4 / judge3
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
sample AC * 2
other AC * 47
権限があれば一括ダウンロードができます

ソースコード

diff #

#include <iostream>
#include <algorithm>
#include <vector>

int64_t modpow(int64_t a, int64_t b, int64_t m) {
    int64_t ret = 1;
    for (; b > 0; b >>= 1) {
        if (b & 1) ret = ret * a % m;
        a = a * a % m;
    }
    return ret;
}

int64_t modinv(int64_t a, int64_t p) {
    return modpow(a, p - 2, p);
}

bool is_square(int64_t a, int64_t p) {
    return modpow(a, (p - 1) / 2, p) != p - 1;
}

int64_t modsqrt(int64_t a, int64_t p) {
    if (a == 0) return 0;
    if (p == 2) return a;
    if (!is_square(a, p)) return -1;
    int64_t b = 2;
    while (is_square((b * b + p - a) % p, p)) b++;
    int64_t w = (b * b + p - a) % p;
    struct P { int64_t x, y; };
    auto mul = [&](P u, P v) {
        int64_t a = (u.x * v.x + u.y * v.y % p * w) % p;
        int64_t b = (u.x * v.y + u.y * v.x) % p;
        return P{ a, b };
    };
    P ret{ 1, 0 };
    P v{ b, 1 };
    for (int64_t e = (p + 1) / 2; e > 0; e >>= 1) {
        if (e & 1) ret = mul(ret, v);
        v = mul(v, v);
    }
    return ret.x;
}

int main() {
    int64_t p, r;
    int q;
    std::cin >> p >> r >> q;
    auto modulo = [&](int64_t a) {
        a %= p;
        if (a < 0) a += p;
        return a;
    };
    while (q--) {
        int64_t a, b, c;
        scanf("%lld %lld %lld", &a, &b, &c);
        int64_t d = modulo(b * b - 4 * a * c);
        if (is_square(d, p)) {
            d = modsqrt(d, p);
            int64_t x1 = modulo((-b + d) * modinv(2 * a % p, p));
            int64_t x2 = modulo((-b - d) * modinv(2 * a % p, p));
            if (x1 > x2) std::swap(x1, x2);
            if (x1 == x2) {
                printf("%lld\n", x1);
            } else {
                printf("%lld %lld\n", x1, x2);
            }
        } else {
            puts("-1");
        }
    }
}
0