結果
| 問題 | No.551 夏休みの思い出(2) |
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2017-07-29 17:54:39 |
| 言語 | C++14 (gcc 13.3.0 + boost 1.89.0) |
| 結果 |
TLE
|
| 実行時間 | - |
| コード長 | 3,073 bytes |
| 記録 | |
| コンパイル時間 | 1,687 ms |
| コンパイル使用メモリ | 114,284 KB |
| 実行使用メモリ | 10,496 KB |
| 最終ジャッジ日時 | 2024-10-10 19:36:48 |
| 合計ジャッジ時間 | 7,986 ms |
|
ジャッジサーバーID (参考情報) |
judge3 / judge1 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | -- * 2 |
| other | AC * 27 TLE * 1 -- * 19 |
ソースコード
#define _USE_MATH_DEFINES
#include <cstdio>
#include <iostream>
#include <sstream>
#include <fstream>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
#include <vector>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <bitset>
#include <numeric>
#include <limits>
#include <climits>
#include <cfloat>
#include <functional>
#include <iterator>
using namespace std;
// 累乗、べき乗
long long power(int a, int b, int p)
{
long long ret = 1;
long long tmp = a;
while(b > 0){
if(b & 1){
ret *= tmp;
ret %= p;
}
tmp *= tmp;
tmp %= p;
b >>= 1;
}
return ret;
}
// a,b の最大公約数と、ax + by = gcd(a,b) となる x,y を求める
long long extgcd(long long a, long long b, long long &x, long long &y) {
long long g = a;
if(b != 0){
g = extgcd(b, a % b, y, x);
y -= (a / b) * x;
}else{
x = 1;
y = 0;
}
return g;
}
// ax ≡ gcd(a, m) (mod m) となる x を求める
// a, m が互いに素ならば、関数値は mod m での a の逆数となる
long long mod_inverse(long long a, long long m)
{
long long x, y;
extgcd(a, m, x, y);
return (x % m + m) % m;
}
/***************************************************************************************************/
// 離散対数問題
// x ^ i ≡ y (mod p) となる i を、Baby-step giant-step algorithm により求める。
// ただし、p は素数。
/***************************************************************************************************/
int discreteLogarithm(int x, int y, int p)
{
int i;
map<long long, int> m;
long long a = 1;
for(i=0; i*i<p; ++i){
if(m.find(a) == m.end())
m[a] = i;
a *= x;
a %= p;
}
long long b = mod_inverse(a, p);
long long z = y;
for(int j=0; j<p; j+=i){
if(m.find(z) != m.end())
return j + m[z];
z *= b;
z %= p;
}
return -1;
}
int main()
{
int p, r, q;
cin >> p >> r >> q;
while(--q >= 0){
int a, b, c;
cin >> a >> b >> c;
// a*x^2 + b*x + c = 0 → (a-s)^2 = t に変換する
long long s = (-b * mod_inverse(2 * a % p, p)) % p;
long long t = (s * s - c * mod_inverse(a, p)) % p;
s += p;
s %= p;
t += p;
t %= p;
if(t == 0){
cout << s << endl;
continue;
}
int e = discreteLogarithm(r, t, p);
if(e == -1 || e % 2 != 0){
cout << -1 << endl;
continue;
}
long long tmp = power(r, e/2, p);
vector<long long> ans;
ans.push_back(((s + tmp) % p + p) % p);
ans.push_back(((s - tmp) % p + p) % p);
if(ans[0] == ans[1]){
cout << ans[0] << endl;
}
else{
sort(ans.begin(), ans.end());
cout << ans[0] << ' ' << ans[1] << endl;
}
}
return 0;
}